Callbacks in JavaScript

Do not miss this exclusive book on Binary Tree Problems. Get it now for free.

A callback function in JavaScript is function where a function passed as an argument to the original function. It is an useful feature in JavaScript
to handle asynchronous operations and much more.

Wait, how can we pass a function to another?

Explaination : First of all we know what a function is and what it does, a function can take some arguments and returns something when it is called/invoked. Now, in JavaScript all functions are objects, hence they can be passed as an argument to other functions and can be called and executed inside the respective function.

Example

let a = function() {
  console.log("World");
};
let b = function(callback) {
  console.log("Hello");
  callback();
};
b(a);

/*
Output:
Hello
World
*/

Output:
Hello
World

As seen in the above line of code we have passed the function a as an argument to the function b and function a is called and executed inside of function b.

Further use cases

  • Simplify function calls
let add = function(a, b) {
  return a + b;
};
let subtract = function(a, b) {
  return a - b;
};
let multiply = function(a, b) {
  return a * b;
};
let divide = function(a, b) {
  return a / b;
};
let calculate = function(num1, num2, operand) {
  return operand(num1, num2);
};
console.log(calculate(4, 2, add));
console.log(calculate(4, 2, subtract));
console.log(calculate(4, 2, multiply));
console.log(calculate(4, 2, divide));


/*Output
6
2
8
2
*/

We can pass the name of the function itself as the argument and use it to call the respective function easily this makes things much easier because even the user can specify the function to be called.

  • Callbacks in callbacks
    Suppose we want to load two scripts one by one,
loadScript('/script.js', function(script) {

  loadScript('/script2.js', function(script) {

    loadScript('/script3.js', function(script) {
      // ...continue after all scripts are loaded
    });

  })

});
  • Callbacks can be used in Animations, Error Handling tasks and many other cases where one operation should take place after the other.

Where to use callbacks in?

In simple words callbacks are used to continue code execution, so instead of waiting for a reply or response from other events javascript continues to execute our code while listening/waiting for other events. This helps a lot in handling asynchronous operations where the execution of one operation doesn't wait for others and is executed immediately.

Advantages of using callbacks :

  • Complex tasks made simple, consider the calculator program above instead of worrying about calling different function each and every time we just passed the name of the function as an argument and were done.
//Normal functions calls

//Enter 1 for addition, 2 for division
add(4,5)
divide(4,2)

//But by using callbacks we can just use the user input for funtion call directly
//enter add for addition 
let add = function(a, b) {
  return a + b;
};
let calculate = function(num1, num2, operand) {
  return operand(num1, num2);
};
console.log(calculate(4, 2, add));
  • Continue code execution without waiting too much time for a response that may are may not respond in future.
  • Carry out asynchronous operations at ease, no worries and no waiting time
download('http://giphy/javascript.gif', handleDownload)
//here handle photo acts as a callback funtion
function handleDownload (error, photo) {
  if (error) console.error('Download error!', error)
  else console.log('Download finished', photo)
}
console.log('Download started')
  • Callbacks like normal functions can be called multiple times, this is a great advantage and time-saver. Callbacks are like functions but just a different implementation to wait for a certain task hence they can be used any no.of times noyhing will change.
  • Callbacks can be used to wait for other events as well this can be very useful to handle asynchronous events in Javascript.
var fn = require('f')

 f.readFile('/Path/Of/TheFile/', handleFile)

 function handleFile (error, file) {
   if (error) return console.error('404 Not found,', error)
   // else we wil continue our work
 }

With this article at OpenGenus, you must have a complete idea of using callbacks in JavaScript which is an important concept. Enjoy.

Sign up for FREE 3 months of Amazon Music. YOU MUST NOT MISS.