Suraj Pheudin

JavaScript Callback Functions - What are Callbacks in JS and How to Use Them

Friday, October 14, 2022

blog theme

Why do we need Callback Functions?

JavaScript runs code sequentially in top-down order. But Wait!, have you ever been to the situation where you need to run a function only after another function has run successfully. Like this condition below:

function add(a, b) {
  setTimeout(() => {
    const sum = a + b;
    return sum;
  }, 2000);
}

function display(value) {
  console.log(value);
}

let result = add(10, 5);

display(result);

Output:
undefined

In this scenario we expect the output to be 15, but we get undefined.

Let's analyze what is going on here.

  • For now we don't have to fully understand the implementation of add function. Let's say add is simply a function which will take 2 seconds to return the value.
  • Then we are declaring a variable result, and assigning it the value returned from add function.
  • Immediately after that, we are displaying the value of result.

Problem

  • The thing to be noticed here is that JavaScript will not wait for 2 seconds before running the line display(result).
  • JavaScript will display whatever the value result variable contains at that time, which is undefined in our case.
  • The value of result is undefined because the add function will take 2 seconds to return the value 15.

To resolve the situations like above, the approach of Callback Function is used.

What is Callback function?

A callback function is simply a function that you pass into another function as an argument for later execution. This technique allows a function to call another function.
Syntax:

function functionA() {
  // Some codes
}

function functionB(callbackFunction) {
  // Some codes
  callbackFunction();
}

functionB(functionA);

Here, functionA can be called as Callback Function because it is passed as an argument in functionB for later execution. Generally later execution means functionA will be called after the other codes in functionB.

Using callback function

Now let's use the callback function to solve the issue that we discussed earlier in this article.

function add(a, b, callbackFunction) {
  setTimeout(() => {
    const sum = a + b;
    callbackFunction(sum);

    return sum;
  }, 2000);
}

function display(value) {
  console.log(value);
}

const result = add(10, 5, display);

Output:
15

In this example, display function is a callback function because it is passed as an argument in function add and is executed after the add function completed the addition of two numbers. That is why we get 15 as an output.

Conclusion

Callbacks are used often in JavaScript, and I hope this article helps you understand what they are and how to actually work with them.