Callback Functions in JavaScript

Photo by Luca Bravo on Unsplash

Callback Functions in JavaScript

·

3 min read

What is a Callback Function?

Let me get started with a simple example. Suppose there is a politician in your area who, before elections in campaigning, gives his word to make better roads. So as to being him capable of making better roads, he needs to win elections first. Similar is the concept with the callback functions. A Callback function is a function that is passed as an argument, which will be executed only after its parent function (the function in which it is passed as an argument) is done executing. In the above example, making better roads serves as a callback whereas, winning elections serves as a parent function. A function is passed as a parameter in another function and calling them inside the outer function.

Why need for Callback Functions?

Callbacks help us in developing asynchronous JavaScript code. As we know, JavaScript is a single-threaded language,i.e, it executes code line after line from top to bottom. So, at certain points in our code, we need a function to be dependent on another function which is also called asynchronous programming. We need callback functions to make sure that a function is only going to get executed after a specific task is completed and not before its completion. Example- event listeners.

//Suppose a button with id 'btn'

document.getElementById('btn').addEventListener('click',handleBody);

function handleBody(){
document.body.style.backgroundColor = 'black';
}

In the above code, the addEventListener() takes the first parameter as a click event and the second as a callback. The handleBody function will only get called or executed after the clicking of the button is done.

Types of Callbacks-

  1. Synchronous Callbacks: Yes, I know callbacks are basically for asynchronous programming but there exist some cases where callbacks get executed synchronously.

     //Synchronous Callbacks
     console.log("First");
    
     function sum(a,b){
     console.log(a+b);
     }
    
     function operation(x,y,callback){
     callback(x,y);
     }
    
     operation(1,2,sum);
    
     console.log("Second");
    
     /* OUTPUT
     First
     3
     Second
     */
    

    In the example stated above, the view from which JavaScript reads is as follows. JavaScript initially logs out the first console.log() present, then goes towards the sum which here acts as a callback. As soon as the operation function is executed, the callback gets executed and at the end, the second console.log() is also logged out. Here all the code has been executed in a synchronous manner.

  2. Asynchronous Callbacks: In asynchronous callbacks, examples such as setTimeout(), and fetching data from the server are pretty common.

     //Asynchronous
     console.log("First");
    
     setTimeout(()=>{
     console.log("Hello World");
     },3000);
    
     console.log("Second");
    
     /* OUTPUT
     First
     Second
     Hello Worl
     */
    

    In the example stated above, when JavaScript runs it, the first console.log() is logged out. Reaching the in-built setTimeout() function which takes the first parameter as a callback and the second as a time. So at that point, JavaScript does not wait for the callback function to get executed, so it moves toward the next line. Thus, logging the second console.log() before the setTimeout(). As soon as the second parameter is achieved in setTimeout, the callback gets executed. This example briefly explained the use of asynchronous callbacks.

That's all about the fundamentals of Callbacks in JavaScript. Next, I will be writing out about the callback hell and Promises in JavaScript.