JavaScript Callback Function

Whenever we pass any funtion as an argument to other function that is called callback function in JavaScript. As you know JavaScript is an asynchronous programming language, it's required that sometime we want to get executes our code once perticular action has been performed. When any function receives function as an argument that will call that function once that functions execution is over. Using callback we can ensure that when our function gets executed at that time it has the all required value.

Example
const displayMessage = function() {   
    console.log("This message is displayed after 10 seconds"); 
} 
  
setTimeout(displayMessage, 10000); 

This code will wait for 10 seconds and will show a message "This message is displayed after 10 seconds". We can also design the callbacks as anonymous function. For example

Example
setTimeout( 
	console.log("This message is displayed after 10 seconds"); 
	, 10000); 

Callback functions are like other normal functions and it can receive an arguments and you can call it from anywhere, any number of times.

 

← Previous