Callbacks in JavaScript

Callbacks in JavaScript

In the Programming world, there are simple functions, a separate piece of code, which performs on the logic we provide them and gets called when we need them.

And then there are Callback functions of Javascript that go the extra mile with their functionality, syntax and ways to use them.

We can pass the functions as a parameter in other functions in Javascript. The reason is that in Javascript everything is an object at its core, and so does the functions. Javascript doesn't have any problem with a function taking another function as its parameter and returning a function too.

Now the function that gets passed are called callback functions. Because they are being called back by the parent function

let name = "Tony Stark";
function print(name, callback) {  
    callback();
};
print(name, callback);

Let's see in the above example, the print function takes 'name' and 'callback' as its parameters, and then the callback function is been called inside the print function.

How these callback functions are useful

You must have heard that Javascript is an asynchronous programing language, which means when the flow control of code is top-down, if javascript encounters any code block which is taking time to complete, Javascript does not wait for it to complete and want to continue with the next lines of code.

This time-taking task can be an external API call to fetch data, some built-in methods like setTimeout, setInterval, reading or writing a file using File System,

function greet() {
 alert('Welcome!');
}
setTimeout(greet, 2000);  
// Here the callback function greet will run after 2 seconds

Callback functions like 'greet' above waiting for the time-taking task and then getting called. Callback functions are useful in the way that they provide the after-math functionality of an API response or a setTimeout task. What needs to be done after we get the response from the API, that work is been carried out by callback functions.

Response to events -

Javascript is an event-driven language, i.e, when on the website a user performs an event like clicking a button, focusing on any input area, submitting a form etc. an event is triggered.

Some logic has to be assigned in response to this event. This logic is then been handled by callback functions. And yeah, you guessed it right, they are passed in the event listener methods of Javascript.

In the example above, handleClick function is passed as the callback function to the button.addEventListener, which just log the "Button is Clicked" text on 'click' event of the button.

document.queryselector("#button")
    .addEventListener("click", function() {    
      console.log("User has clicked on the button!");
});

Also, amazingly we can pass the whole function definition as a parameter, and it works just as same. Now, this you must have not seen in some other language.

See that there is no name to the callback function, the Javascript allows us to use it this way, they are anonymous.

Callbacks ensure that the function will not run before the task is completed but will run right after the task is completed. It develops asynchronous JavaScript code and keeps them safe from error.

The above code can be written using Arrow functions, and this is the more conventional way of passing callback functions. It works the same as before, just more syntax free.

document.queryselector("#button")
    .addEventListener("click", () => {    
      console.log("User has clicked on the button!");
});

Wrap Up

Callbacks are used often in JavaScript, and I hope this post helps you understand what they actually do and how to work with them easier.

You can read more on how to handle callbacks, what is nested callbacks and how to tackle them using promises and async-await.