An Introduction to JavaScript Callbacks β

Search for a command to run...

Glad you liked it! π
(This article was primarily written for another blog. The language of this article is more formal. Please let me know your thoughts through the comments.) Writing better and high-quality code is essential. Better code makes software stable and seamle...

This article is going to be a fun one. In this article, we'll be building a Tic Tac Toe game just by using HTML, CSS, and JavaScript. This is going to be an easy one. Both the inputs have to be placed by the user. But in another article, we will be c...

I am sure at some point in your life while browsing the web, you have found a web page that shows an animated counter. A counter that starts from 0 and goes all the way up to some given number. Here is an example of how such a counter looks. In this...

Building a JavaScript project always gives an excellent overview of the internals of the language. And also, it helps to make the portfolio better. In todayβs article, we will be building a fantastic mini JavaScript project. We aim to develop a Passw...

Building a Weather app with JavaScript is an excellent project for beginners. It helps to understand the core basics of the DOM and teaches how to use fetch API, to call and get data from a third-party service. In this tutorial, we'll be building a g...

We know that in JavaScript, we can pass functions as an argument into another function. These functions which take other function as an argument are known as Higher-Order functions. And the functions which are passed as an argument are known as a Callback function.
I've discussed three higher-order functions in this article. π
JavaScript uses a single-threaded non-blocking event loop to provide concurrency. Which means, rather than waiting for a function to complete its execution, it'll execute other function on the event loop first.
Let's check an example,
let first = () => {
console.log("I'll Run First");
}
let second = () => {
console.log("I'll Run Second");
}
first();
second();
I'll Run First
I'll Run Second
This output was expected. What if the first function needs some time to execute? Suppose the first function is an API call, which takes more time than usual? Will our code work in the same top-down approach as before?
Let's create such an instance using the setTimeout() function. What setTimeout do is it evaluates an expression after a given time.
let first = () => {
setTimeout(() => {
console.log("I'll Run First");
}, 500);
}
let second = () => {
console.log("I'll Run Second");
}
What we are doing here is, we are delaying the first function by 500 milliseconds by calling the setTimeout() function.
If we call the function first and second in the previous order now, we should get the same result as before.
first();
second();

But to our surprise, the second function will execute first this time. So, in this case, JavaScript didn't wait for the first function to complete, rather it executed the second function first. JavaScript doesn't always execute in the order they are called. This is because JavaScript is an event-driven language. We'll discuss the event loop in some future article.
But the key takeaway from here is we just can't hope that JavaScript will execute the functions in the order we called them.
Now, what if we want to complete a function execution and only then we want to jump to the next function? The callback comes to rescue here. β
Callbacks make sure that another task doesn't run before a task is completed.

To create a callback function, we usually name the argument callback or cb and pass it as the last argument of the function. Let's see how we can modify our old code to a new callback function.
let callMeFirst = (callback) => {
console.log("I'll run first");
callback();
}
let callMeFirst = (callback) => {
console.log("I'll run first");
return callback();
}
Now our function is ready to accept a callback function. We can call another function as a parameter in our callMeFirst function now. And the other function passed as the second parameter will always be called after the first function executes.
callMeFirst(() => {
console.log("I'll run second");
});
Here, we are passing an anonymous function as a parameter in the callMeFirst function.

Here, the callback function is an anonymous function. We can also define a named function and pass it as a callback.
let callMeFirst = (callback) => {
console.log("I'll run first");
callback();
}
let callMeSecond = () => {
console.log("I'll Run second");
}
callMeFirst((callMeSecond));

We just passed a named function as a callback in the above example.
I'd suggest using named functions over anonymous functions as callbacks because it makes the code more readable and also the named functions can be used anywhere in the code.
I hope this article put some light on your understanding of what are callbacks and how to use them. If you liked the article, or it helped you leave a β₯, share it and leave a comment. π