JavaScript Callback Functions

JavaScript Callback Functions

ยท

3 min read

This blog covers in depth about callbacks, advantages of using callback function, what does blocking the main thread means, garbage collection and why to remove event listeners. We will also see an example of callback function using setTimeout and an example of closure with event listener. This knowledge will be very helpful for understanding the event loop and how javascript works asynchronously.

So Let's Get Started

We know that, functions are first class citizens in javascript i.e we can take function and pass it into another function and when you do so, the function which you pass into another function is called as callback function.

These callback functions are very powerful in javascript, it gives us access to the whole asynchronous world in a synchronous single threaded language. (synchronous single threaded means, it can do one thing at a time and in a specific order)

Due to callback we can do async things inside javascript.

Example :-

function x(y){
    // code
}
x(function y(){
    // code
}

In this example, function y is callback function

Now let us see, how this callback function is used in asynchronous task.

Consider Below Example :-

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

Output :-

x
y
timer

As javascript is single threaded language, so code will execute one line at a time and in specific order. Here, first thing will happen, registering a setTimeout, so setTimeout will take a callback function and store it in a separate space and will attach a timer of 5000 milliseconds. As we already know, javascript waits for none. So here, javascript will not wait for setTimeout to finish, that is why we say callback function gives us power of async things, i.e. it does not wait for 5000 milliseconds and will move to next part of code, it will see a function definition of x and then it will try to call function x by passing function y and will execute code. So first, it will print console.log("x") and then console.log("y"). After some time 5000 millisecond expires and then callback function gets executed.

So, setTimeout asynchronous operation was not possible without callback.

Blocking Main Thread in JavaScript

JavaScript has just one call stack and we call it as main thread. So whatever is executed inside your page is executed through call stack only. So if any operation blocks the call stack then it is called as blocking the main thread in javascript. We should never block our main thread, instead we should use async operation for things which takes time.

Example of Closure With Event Listener

function attachEventListeners(){
    let count = 0;
    document.getElementById("clickMe")
    .addEventListener("click", function xyz(){
        console.log("Button Clicked", ++count);
    });
};
attachEventListeners();

Button Clicked 1
Button Clicked 2
so on........

The reason why we have declared count variable inside attachEventListeners function is because, declaring it in global space is not a good practice. And when we declare it inside function then we get advantage of data hiding. Here, function xyz is callback function, whenever user clicks on button, this xyz function gets executed and at the same time callback function increases the count and this is due to closure.

Garbage Collection & Remove Event Listener

Why do we need to remove event listener?

First of all, event listeners are heavy i.e. it takes memory. So whenever you attach any event listener, it kind of forms a closure and even when call stack is empty, still our code does not free up memory because of event listener attached. So in this case, we cannot free up this extra memory and that is why event listeners are heavy. And this is the reason, why we remove event listeners when we are not using them.

So, when we remove the event listener then all the variables which were held by closure will be garbage collected.

Hope you liked this!

Let's Get Connected ๐Ÿค:)

ย