Callback Function in Java Script

Definition

Function passed as an paramter to other funtiom is known as callback function.

Eg:
function x(y) {
  console.log("x");
  y();
}

x(function y() {
  console.log("y");
});

//here function y is passed inside function x , hence function y becomes a callback function.
 

Explanation

Everything inside javascript is an object, so the object can be passed as an argument, hence function can be passed as an argument.

Need for the callback function

Javascript is a single-threaded synchronous language, meaning it executes the code line by line from top to bottom. But sometimes, we need to execute something only after some action has been done, in that case, we need to break that line-by-line code execution and that is when callback comes into the picture and that’s when asynchronous behavior of function also comes into the picture.

Now what is asynchronous function means in Java Script

In simple terms, when more than one execution is going on simultaneously, that is asynchronous, meaning one operation can occur while another one is still being processed.

Real example – When you upload a reel/image on Instagram, you can see the reel show uploading a top, and at the same time, you can browser and do other stuff on Instagram at the same time. This is asynchronous behavior, meaning a parallel task or action is taking place simultaneously.

Let’s understand this with a code –

const message = function () {
  console.log("This message is shown after 3 seconds");  //1
};

setTimeout(message, 3000);

function x(y) {
  console.log("x");
  y();
}

x(function y() {
  console.log("y");
});
//Explanation - setTimeout is an function , message is an anonymouse function , so function called inside an function.
//Here message is an cb function
 

Explanation of the above code

  • Here message function is a cb function and setTimeout is an async function.
  • The message function will not be executed because setTimeout has kept hold for 3 sec, i.e async behavior
  • Now according to async behaviors, the js engine will move to the next line, and the above setTimeout function will keep on running simultaneously.
  • Now again function x takes y as a callback
  • Now first “x” will be printed, then y is called, so “y” will be printed and then after 3 sec, message function output will be printed.

Summary, if a function is called as a parameter in another function, it means callback. Also, callback helps in making a function asynchronous.

Hope this article helped.

Thanks for reading.

Help Others

Leave a Reply

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