JavaScript Callback Function

A function that is passed as an argument to another function is known as callback function. This means, callback functions are just any JavaScript function, but that can be used as an argument to another function.

Callback functions are examples of higher-order functions: functions that accept other functions as arguments or return functions. Higher-order functions are a powerful pattern in JavaScript for composing behavior.

Callback Function Example

hi


function main(x){
        x();
}
function callback(){
    console.log("hi");
}
    
main(callback);            
        

In the above example, main is a function with parameter x. Inside main function, we are calling x. This means x should be a function, not any other datatype. Argument of main function is callback. The above example is synchronous callback as the code execute immediately.


Synchronous Callback

Synchronous callback is a callback where code execute immediately, i.e. synchronously. All the code in main thread will be executed line by line. See example

Synchronous Callback example

Show is at 9

Show Ends

done


function showTime(x,done){    
    console.log(" Show is at ", x);
    done();
}
    
function showEnd(){
    console.log("Show Ends")
}

showTime(9,showEnd);
console.log('done')

The above code will execute line by line. That's why, the last line, i.e. console.log("done"); executes in the end. That's why, it is called synchronous callback.

callback in array

To filter or sort array, use Arrow Function as callback. Array callback functions are also synchronous by default.

[2,4,8]

done


const num=[1,2,4,8,11];
const even=num.filter(i=>i%2==0);

console.log(even);
console.log('done')

callback function used in arrays are also synchronous.


Asynchronous Callback

Asynchronous callback is a callback where code within callback function is executed after main thread is completed. Event Loop handle all the asynchronous operations in JavaScript. For asynchronous callback, we can use any one of below techniques in javascript.

Asynchronous techniques in javascript

  1. setTimeout / setInterval
  2. events
  3. ajax/fetch
  4. Promises
  5. async await

Event Loop

Event Loop is the runtime model on which javascript is based. By default frontend javascript is synchronous. But using Event Loop, we can run asynchronous programs in javascript.

Asynchronous callback is one of the main reason behind performance of JavaScript. The main thread executes synchronous code first and the long waiting tasks are kept inside asynchronous functions using Event Loop, like setTimeout timing function with callback. All non blocking methods are executed using Event Loop which use Asynchronous callback in JavaScript and Node JS.

To avoid callback hell, we will use JavaScript promises for efficient asynchronous operations.

How event loop works?

JavaScript Event Loop
JavaScript Event Loop

The call stack executes synchronous code first while the page is initially processed. During this time you may see a loading spinner or progress indicator in the browser. When the document is ready and the main thread is free, asynchronous callbacks (scheduled earlier) are pulled from the task queue and executed by the event loop.

Once an event is triggered, like when we click a button, the event loop places the callback function on the Task Queue (a.k.a. callback queue). The task queue waits for the call stack to be free; once it is, the task is moved to the Call Stack and executed. Note: Promises use the microtask queue, which runs before the task queue.

Many systems use similar non-blocking techniques — for example, Node.js uses an event-loop model for I/O, and web servers like nginx are designed for high concurrency using efficient, event-driven designs.


Synchronous Vs Asynchronous

Synchronous code

1

2

3


console.log(1);
setTimeout(console.log(2));        
console.log(3);

Asynchronous code

1

3

2


console.log(1);
setTimeout(()=>console.log(2));
console.log(3);

Asynchronous using promise

Javascript Promises are meant for asynchronous programming. We will learn Promises in detail in upcoming sessions.

2

1


    const p=Promise.resolve(1);
    p.then(i=>console.log(i));
    console.log(2);

Parameters in callback function

To pass parameters in callback function, we need to parameter in parent function first and then pass it to callback function. See example

Class starts at 10

Projector running using hdmi


    function startClass(x,y,z){    
        console.log(" Class starts at", x);
        y(z);
    }
    
    function onProjector(x){
        console.log("Projector running using ", x)
    }

    startClass(10,onProjector,"hdmi");
    

In the above example, startClass is the main function and onProjector is the callback. First parameter is parameter of startClass, second parameter is callback function and third parameter is parameter of callback function.

In ES6, we can use JavaScript Promise to handle long and nested Asynchronous operations.

Frequently asked questions

What is a callback in JavaScript?

A callback is simply a function passed as an argument to another function, which can be invoked inside the outer function to complete a task or signal completion.

Are callbacks synchronous or asynchronous?

Callbacks can be both. A callback that runs immediately inside the calling function is synchronous. Callbacks scheduled via timers, events, or I/O are asynchronous and are run later by the event loop.

How do I avoid callback hell?

Use Promises and async/await to flatten nested callbacks and to make asynchronous code easier to read and maintain.

See also