Javascript Callback Functions In Depth Guide for 2019

Profile image for Srikanth
Srikanth JavaScript Enthuthiast
Oct 14, 2021 ‧ 7 min read

Javascript callback functions; another important concept you must need to understand. Otherwise, you might face lot of struggles for becoming a successful javascript developer. But I am sure that after reading this article thoroughly you will be able to overcome any obstacles you previously had with callbacks.

Before, I will talk more about callback function, but at first, you need to have some minimal level of knowledge about functions. I mean you should know what a function is, how it actually works, what are different types of functions etc.

A Quick Recap: Javascript Function

What is a Function?

A function is a logical building block inside of which a set of codes are written in order to perform a specific task. Practically, functions allow writing codes in more organized way that is also easy to debug and maintain. Functions also allow code reuse.

You define function once, and call it when you need to without writing the same codes again and again.

Syntax for Declaring a Function

We talked a little about what a function is. Now, let's see how to declare a function in javascript.

Using Function Declaration Statement: Actually, this method is the old school method that is used commonly in javascript. Here, after the keyword "function" you have to specify the name of the function. After that, if the function accepts multiple parameters or arguments; you need to mention them too. Although this part is completely optional.

In the body of the function, the function must return a value to the caller. After a return statement is found, the function will stop executing. Inside the function, the parameters will act as a local variable.

Also, the variables that are declared inside the function will be local to that function. Local variables can be accessed within that function only, so variables with the same name can easily be used in different functions.

What is Javascript Callback Function?

As per MDN: A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.

I know after reading this technical definition, you are confused and hardly able to understand what is actually a callback function.

Let me clarify this with simple words, a callback function is a function that will be executed just after another function has finished executing. Callback function is a function that is passed as an argument to another javascript function. That callback function is executed inside of the function it was passed into.

In javascript, functions are treated as first-class objects. By saying first-class object, we mean that a number or a function or a variable, can be treated as same as any other entity in the language. Being a first-class object, we can pass functions to other functions as variables and functions can be returned from other functions too.

Functions that can do this is known as higher order functions. A callback function is actually a pattern. The word "pattern" means some sort of proven methodology to solve a common problem in software development. There it is better to call the use of callback function as a callback pattern.

Why We Need Javascript Callback?

The client-side javascript runs in browser and the main browser process is a single threaded event loop. If we try to execute long-running operations within a single-threaded event loop, the process is blocked. This is technically bad because the process stops processing other events while waiting for your operation to complete.

For example, "alert" statement is considered as one of the blocking codes in javascript in the browser. If you run alert; you can no longer do any interaction within the browser, until you close the alert dialog window. In order to prevent blocking on long-running operations, callback is used.

Let's dive deep so that you will understand exactly in which scenario callback is used.

In the above code snippet, getMessage() function is executed at first and then displayMessage() is executed. Both displayed a message in the browser's console window and both of them executed immediately.

But in certain situations, some codes are not executed immediately. For example, if we assume that getMessage() function performs an API call where we have to send the request to server and wait for the response, then how we will be able to deal with it ?

Simple, to handle that kind of scenario, we need to use callback functions in javascript.

How To Use Javascript Callback Function?

Rather than telling you about the syntax of javascript callback functions, I think it would be better if we try to implement callback function on our previous example. The code snippet is shown below in the following screen shot.

How Javascript Callback Works?

Let me explain what actually happened behind the scene in the previous example.

As you can see from the previous example, in the getMessage() function, we are passing two arguments; first argument is the "msg" variable which gets displayed in the browser's console window and second argument is the "callback" function.

Now, you may wonder why "callback" function is passed as the argument. It's because to implement callback function, we must pass a function as an argument to another function.

After getMessage() function finishes it's task, we are calling that "callback()" function. After that when we are calling getMessage() function, we passed reference to "displayMessage()" function, which is treated as a callback function.

Note carefully that, when getMessage() function is called, we are only passing the reference to the "displayMessage" function. That's why, you will not see the function invoke operator i.e, "()" beside it.

Is Javascript Callback Asynchronous?

Javascript is considered as a single threaded scripting language. By the term "single threaded" it means that javascript execute one code block at a time. When javascript is busy executing one block, it is not possible for it to move to next block.

In other words, we can say that javascript code is always blocking in nature. But this blocking nature, prevents us to write code in certain situations when we are not able to get immediate result after running some specific tasks.

I am talking about tasks such as following.

Sending API call to certain endpoint for getting data.

Sending network request to get some resource (for example, text file, image file, binary file etc. ) from a remote server.

To handle these situations, we must write asynchronous codes and callback function is one approach to deal with these situations. So, callback functions are asynchronous in nature.

What is Javascript Callback Hell ?

Callback hell occurs when multiple asynchronous functions are executed one after another. It is also known as pyramid of doom.

Let's assume, you want to get list of all github users, then among the users you want to search for only top contributors for javascript repository. Then among the persons, you want to get details of the person whose name is Jhon.

To implement this functionality with the help of callbacks, the code snippet will be similar as shown below.

Posted on Oct 14, 2021 by:
Profile image for Srikanth
Srikanth
JavaScript Enthuthiast

Comments

Profile image for Srikanth

JavaScript Enthuthiast

15
Reputation
0
Following
39
Followers