An Introduction to JavaScript Callbacks โš”

An Introduction to JavaScript Callbacks โš”

ยท

3 min read

What is a Callback function? ๐Ÿค”

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();

Output:

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.

Example:

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();

Output

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.

Creating a Callback ๐ŸŽจ

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.

Example:

let callMeFirst = (callback) => {
  console.log("I'll run first");
  callback();
}

Or,

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.

Output:

Here, the callback function is an anonymous function. We can also define a named function and pass it as a callback.

Example:

let callMeFirst = (callback) => {
  console.log("I'll run first");
  callback();
}

let callMeSecond = () => {
  console.log("I'll Run second");
}

callMeFirst((callMeSecond));

Output

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. ๐Ÿ˜Ž

Did you find this article valuable?

Support Subha Chanda by becoming a sponsor. Any amount is appreciated!