Skip to main content

Command Palette

Search for a command to run...

Callbacks in javaScript

Updated
3 min read

In the javaScript callback functions are play important role maximum time it is used even we don't know about it but we use with .then ,.catch ,Promises, filter, map and many more. There are two types of callback Synchronous and Asynchronous we will cover it later.


What is callback function?

  • It is a function which passed as an argument to another function.

  • It is called after a particular task.

function greet(name, callback){
    console.log(`Welcome ${name} !`);
    callback();
}

function goodBye(){
    console.log(`Nice to meet you`);
}

greet("Happy singh", goodBye);

goodBye function pass as an argument to greet function and call after a particular task.


Why callbacks are used in asynchronous programming?

  • In asynchronous callbacks are used to handle operations that take time like network call, timers.

  • Prevent to block main thread.

  • A callback function can passed value to another callback function so the each callback depend on other callback ( this create a problem called callback hell ).

console.log("start");

setTimeout(() => {
    console.log("setTimeout function");
}, 1000);

console.log("end");

// Output: start, end, setTimeout function

it is example of asynchronous code first the both of console will print and then the setTimeout because it is handle by webAPI.

function findEmployee(id, callback) {
    setTimeout(() => {
        console.log("Find user and id: ", id);
        callback("Happy");
    }, 1000);
}

function employeeName(name, callback) {
    setTimeout(() => {
        console.log("Employee name: ", name);
        callback(100000, "software developer");
    }, 1000);
}

function employeeSalary(salary, designation, callback) {
    setTimeout(() => {
        console.log(`Designation: \({designation} | Salary: \){salary}`);
        callback();
    }, 1000);
}

findEmployee("Emp101", (name) => {
    employeeName(name, (salary, designation) => {
        employeeSalary(salary, designation, () =>{
            console.log("All steps completed");
        });
    });
});

This is the just the example use setTimeout for delay the process so don't get confuse.


Problem with callback

findEmployee("Emp101", (name) => {
    employeeName(name, (salary, designation) => {
        employeeSalary(salary, designation, () =>{
            console.log("All steps completed");
        });
    });
});

This is the main problem with callback functions this is called callback hell that's why after a particular point we avoid the callback functions and use async await

  • It is hard to debug.

  • Difficult to modify.


Callback usage in common scenarios

We can not properly neglect the callback event it needs most of times:

  • Event handling in the browser

  • Array methods map, forEach, filter.

  • Network call fetch .then catch.