You are currently viewing A good example to understand the callback function in JS

A good example to understand the callback function in JS

Callback Function Example in JavaScript

In this article, we are going to learn about the callback function in JavaScript with Example. In JavaScript function are first class objects. That means Just like an object, a function can be passed as an argument to a function and a function can also be returned as values from another functions. Let’s understand with a simple example:

Ex:

function greet(name){
   console.log('Hello ${name}')
} 

function greetjohn(greetfn){
   const name = "John"
   greetfn(name)
}

greetjohn(greet)
  1. Here, we have a function called greet(), which accepts a “name” parameter and logs to the console “hello” followed by “name”.
  2. And then we have another function called greetjohn(), what is special here is that the function accepts another function as its arguments. Within the function body, we have a const declaration (name = “john”) and we called the passed in function with “name” as its arguments. Finally, we invoke “greetjohn()” passing in the greet function.
  3. So, the control goes to greetjohn() , which calls greetfn. The greetfn is nothing but the greet function we have defined. Execution goes to the greet function with name = ‘john’. So, greetjohn is a function which accepts another functions as arguments.

And you might be pleasantly surprised to learn that any function that is passed as an arguments to another function is called a Callback function in Javascript. Also the function which accepts a function as an argument or retruns a function is called a higher order function.

If we simply rename the function and it argument like below code. Here on line 5 we have higher order funciton which accepts the callback function. On line 7 calls that callback() function passing in the name constant.

function greet(name){
   console.log('Hello ${name}')
} 

function higherOrderFunction(callback){
   const name = "John"
   callback(name)
}

higherO$rderFunction(greet)

Why do we need a callback function?

We can answer that by categorizing callbacks into two: they are :

  1. Synchronous callbacks
  2. Asynchronous callbacks
READ ALSO  Javascript if Statement Multiple Conditions

Synchronous Callbacks

A callback that is executed immediately is called a synchronous callback. A greet() callback function from earlier code is an example because the function gets executed immediately when the control goes inside the higher-order function. A practical example is a callback function passed to method like sort, map or filter. In these cases the callback function defines the logic that the higher order function needs to apply.

Asynchronous callbacks

It is a callback that is often used to continue or resume code execution after an asynchronous operation has completed. So in the async world callbacks are used to delay the execution of a function until a particular time or event has occured. And this case is really important because most of the applications that we build usually have some sort of data to be fetched. We all know that data fetching takes time and we can only run the function we want to after the data has been fetched and not immediately.

Example:

callback function example in javascript

In the above code, we set timeout acts as the higher order function and greet is a callback function.
When thread of execution goes through line no 5, the greet function execute immediately?
No, it waits for 2 seconds and then executes the greet callback function making it an async callback.

callback function example in javascript

And another common usage is event handlers. When JavaScript encounters line number 5, it doesn’t immediately run the callback function. The function is only run when the user clicks on the button. So, this is the role that callback function plays in async JavaScript. They allow you to delay the execution of a function.

READ ALSO  Easy Ways to Add Hours to Date in JavaScript

Problem with the callbacks pattern

If you have multiple callback functions where each level depends on the result obtained from the previous level, the nesting of function becomes so deep that the code becomes difficult to read and maintain. In the below code, we can see that each inner function depends on the result obtained from outer function. So once you go several levels deep like on line 5 in below code, the nesting starts to confuse. The code is just not intuitive and only gets worse with more and more callback functions as the application grow.

callback function example in javascript

To tackle this problem of callback hell, promises were introduced in ES6.

Leave a Reply