Callbacks in Javascript

Callbacks in Javascript

Functions are called first-class citizens in Javascript which means you can pass it to another function as an argument and this function which you pass as an argument is known as a callback function.

function outer(callback){

}

outer(function inner(){
    console.log("I am a callback function")
})

Here, in above code inner() is a callback function.

Why callbacks??

Callback functions are very powerful in javascript and it gives us access to a whole asynchronous world in the synchronous threaded language.

JavaScript runs code sequentially from top to bottom. However, there are some cases that code runs (or must run) after something else happens and also not sequentially. This is called asynchronous programming.

Callbacks make sure that a function is not going to run before a task is completed but will run right after the task has completed. It helps us develop asynchronous JavaScript code and keeps us safe from problems and errors.

With the help of a callback function, we can perform asynchronous things inside javascript.

Let's see an example

setTimeout(function (){
    console.log("from timer");
},3000);

The function which you passed as the first parameter to setTimeout is a callback function. Second parameter it takes is time in millisecond which indicates after how much time the callback function is executed.

one more example :

setTimeout(function (){
    console.log("inside timer");
},5000);

function outer(callbackFn){
    console.log("outer function");
    callbackFn();
}

outer(function inner(){
    console.log("inner callback function");
})

In the above example:

As Javascript is the synchronous single-threaded language that means code is executed one line at a time and in order. Firstly, setTimeout will take this callback function and store it in a separate space and attach a timer to it of 3000 ms and execute it after the time expires. As you know, Javascript won't wait for setTimeout to finish and execute the next line of code and hence prints the outer function in the console. Then it executes the callback function callbackFn which is passed as an argument to the outer function and prints the inner callback function in the console. After setTimeout 3000 ms timer expires, it prints inside timer in the console. Javascript has only one Call stack also known as main thread. Anything which is executed inside your code is actually executed through the call stack behind the scene. So if any operation blocks the call stack then it is known as blocking the main thread.

That is why we need to perform async operations to take out the time-consuming code from the call stack and prevent blocking the main thread. And setTimeout and callback functions perform an important role here and helps to achieve the asynchronous operations.