See all blogs

Callback in javascript

Callback in javascript

A callback function is a function passed into another function as an argument. This function is invoked inside the outer function to complete an action. Let's take a simple example of how to use callback function

function callbackFunction(name) {
  console.log("Hello " + name);
}
 
function outerFunction(callback) {
  let name = prompt("Please enter your name.");
  callback(name);
}
 
outerFunction(callbackFunction);
 

Why do we need callbacks

The callbacks are needed because javascript is an event driven language. That means instead of waiting for a response javascript will keep executing while listening for other events. Let's take an example with the first function invoking an API call(simulated by setTimeout) and the next function which logs the message.

function firstFunction() {
  // Simulate a code delay
  setTimeout(function () {
    console.log("First function called");
  }, 1000);
}
function secondFunction() {
  console.log("Second function called");
}
firstFunction();
secondFunction();
Second function called
First function called

As observed from the output, javascript didn't wait for the response of the first function and the remaining code block got executed. So callbacks are used in a way to make sure that certain code doesn’t execute until the other code finishes execution.

Types of Callbacks

  • Synchronous Callbacks: These are executed immediately after the outer function is invoked. For example, callbacks used in array methods like map() and forEach().
const numbers = [1, 2, 3, 4, 5];
 
function processArray(arr, callback) {
    arr.forEach(callback);
}
 
function logNumber(number) {
    console.log("Number: " + number);
}
 
processArray(numbers, logNumber);
 

Output:

Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
  • Asynchronous Callbacks: These are executed at a later time, typically after an asynchronous operation has completed. Examples include callbacks used with setTimeout() and Promises.
function fetchData(callback) {
    console.log("Fetching data...");
    setTimeout(() => {
        const data = "Data received";
        callback(data);
    }, 2000); // Simulates a 2-second delay
}
 
function handleData(result) {
    console.log("Callback executed: " + result);
}
 
fetchData(handleData);

Output:

Fetching data...
// After 2 seconds
Callback executed: Data received

Callback hell

Callback Hell is an anti-pattern with multiple nested callbacks which makes code hard to read and debug when dealing with asynchronous logic. The callback hell looks like below,

async1(function(){
    async2(function(){
        async3(function(){
            async4(function(){
                ....
            });
        });
    });
});

Key Points to Remember

  • Higher-Order Functions: Functions that take other functions as arguments or return them are called higher-order functions. The main function in the examples above is a higher-order function.

  • Anonymous Functions: Often, callbacks are defined as anonymous functions, especially in asynchronous operations.

  • Closure: Callbacks can access variables from their outer scope, even after the outer function has completed execution.

Real-Life Applications

  • Loading Resources: Callbacks are used to load images or data asynchronously, allowing the rest of the application to function without waiting for these resources to load.

  • Handling User Interactions: Callbacks can manage events like form submissions or button clicks, ensuring that the application remains responsive while processing user input.

ruhulamin© 2025 All rights reserved.