Header Ads

JavaScript Callback Function

What is a callback? A callback is a function excuted after another function has finished executing("call back"). 

Because in JavaScript functions are first class objects they can take other functions as arguments. Any function that is passed as an argument is called a callback function
JavaScript Callback Function
Why use Callbacks?

1. Use callback to execute some function immediately after the other function(Synchronous callback). 2. Continue code execution after an asynchronous operation has completed(asynchronous callback),e.g. after a promise fulfills or rejects. 

Simple Example: Remember, a callback is a function that is to be executed after another function has finsihed executing.
const message = function() {
  console.log("5 sec delay");
}
setTimeout(message,5000);
Here the message function is being called after 5000 milliseconds(5 sec). So the message function gets called after something else happen and it is there fore an example of a callback function. 

Example in Browser: Here we told JavaScript to listen for the click event on a button. When button gets clicked, JavaScript should fire the function(e).
const button = document.querySelector('button')
button.addEventListener('click',function(e) {
// Adds "red" class to button
this.classList('red')}) 
So in this case function(e) is the callback while "addEventListener" is a function that accepts a callback.

No comments:

Powered by Blogger.