Callbacks in JavaScript

Prachi
3 min readOct 3, 2020

Hello people!💗 This article is about one of the most important interview question -callbacks and promises✌.

Functions in JavaScript are objects. Because of this, functions can take functions as arguments and can be returned by other functions. Any function that is passed as an argument and called by the function that receives it, is called a callback function.

Wait, What!!🎃

Let’s see-

Operations in JavaScript are executed from top to bottom(synchronous). For instance-

You will get the following in console-

Now suppose Work Hard takes some time, let’s change the code a bit.

You will get the following in console-

The whole operation doesn’t pause for 3 seconds to log “Work Hard” so it can. Rather, the JS engine goes ahead to log “Give Interviews” and “Get your dream job”, after 3 sec it logs “Work Hard”. This is called asynchronous operation.

But what if I want the JS engine to wait for “Work Hard ” and then execute the next lines???đŸ€”

You can imagine some real-world situations like- if you are calling an API and you want the next lines to be executed only when the response from API comes(which takes some time).

This is where callbacks come!

Callback

In the console, you will get -

Let’s see one more example-

Output is -

Make weather = true, output is-

Note: The callback function is not run unless called by its containing function, it is called back. Hence, the term call back function

Let’s see another example-

or you can write it as-

A callback is important here because we need to wait for a response from the server before we can move forward in our code. We don’t know if our API request is going to be successful or not. Once API responds, our callback function is invoked.

Callback hell

Till now we have seen callback is used to wait until the API gets you the data. But what if you want to use that data to make some other request within the callback function???

In the above example, we have a callback in a callback in a callback. The code is less readable and messier. In some cases, you may have a callback in a callback in a callback or even a callback in a callback in a callback in a callback. GOD! IT IS MESSY!

Here comes the concept of Promises! We will deal with it in the next article.

Thank you for reading!đŸŒșđŸŒș

--

--