Loading...
JavaScript

What is Callback in JavaScript

callback is a plain JavaScript function passed to some other function as an argument or option. In JavaScript, functions are objects. Because of this, a function can take another function as a parameter and calls it inside. This is why we call it a “callback“. Let’s understand this with an example:

var message = function() {  
    console.log("This message will be shown after 1 second");
}
setTimeout(message, 1000); // message is callback function here

A callbacks could be anonymous function too. We can define a function directly inside another function, instead of calling it. Checkout the following example:

setTimeout(function() {  
    console.log("This message will be shown after 1 second");
}, 1000);

The output of the above two examples will be same.

Callback Using ES6 Arrow Function:

setTimeout(() => { 
    console.log("This message will be shown after 1 second");
}, 1000);

Note: The setTimeout is JavaScript’s inbuilt function which calls a function or evaluates an expression after a given period of time (in milliseconds).

Thank you for reading. If you found this article helpful, please leave your thoughts in the comment box below.

Share this article with your friends
Leave a Reply

Your email address will not be published. Required fields are marked *