Callback in JavaScript: The Complete Guide

3
190
Callback in Javascript

In JavaScript, functions are objects. Because of this, functions can take functions as arguments and can be returned by other functions. Functions that do this are called higher-order functions. Any function that is passed as an argument is called a callback function. So, we can use it as a variable like Strings and ObjectsIf they are variables, then we can do the following with them.

  1. Passing functions as an argument to the function.
  2. Return function from a function.
  3. Storing the anonymous functions into the variables.

Callback in JavaScript

A function is passed to another function as an argument, and the given function is executed inside the other Function and that parameterized function is called Callback. We have often used callbacks, especially in jQuery, where we listen from the DOM event and pass the Callback to that function. For example

Example #1

jQuery("button").click(function() {
  alert("Clicked");
});

When we click the button at the same time click event is fired, and we pass the Anonymous Function as a parameter, and that Anonymous Function is called Callback. So in this example, the click function’s argument is another function. So another function is a callback.

Wherever click event happens, the parameterized function will be executed, or in other words, the Callback is executed.

We can also store the function into the variable like,

//main.js

let mj = () => {
    return 'mj';
}
console.log(mj());

In the above example, we have stored the function into the variable called mj, and later we called it, and then in a console, we can see “mj“. I have used the arrow function, which is a new ES6 feature in Javascript 

If you are directly running the above code in the browser, you might face the following issue.

Possible Errors

  1. You can get any syntax errors.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put the above code in the main.js file.

Example #2

//main.js

let dance = (param) => {
    return `MJ is ${param}`;
}
let sing = (param) => {
    return `MJ is ${param}`;
}
let mj = (param, fn) => {
    return fn(param);
}
console.log(mj('singing', sing));
console.log(mj('dancing', dance));

Output

MJ is singing
MJ is dancing

In the above example, we have first defined two functions. dance() and sing().

Next, we have created one more function called mj(), which accepts two arguments.

  1. singing/dancing as a string
  2. Anonymous Function or Callback

Callback functions are none other than the previously defined two functions.

  1. dance()
  2. sing()

So, in our case, dance() and sing() are callbacks.

Example #3

//main.js

setTimeout(()=> {
    console.log('1st');
    setTimeout(()=>{
        console.log('2nd');
        setTimeout(()=>{
            console.log('3rd');
        }, 1000);
    }, 1000);
},1000);

In the above example, we have used the setTimeout event, which is Asynchronous and entirely dependent on a specified time interval. Herein also, the setTimeout event accepts two parameters.

  1. Anonymous Function
  2. Time(milliseconds)

At the given time interval function is fired and logs the statement.

Output

1st
2nd
3rd

Memorable Points

  1. One point to remember is that we are not executing the function in the parameter; we are only passing the function definition. The parameterized function is executed inside the primary function.
  2. If you have read my Closures article, the insider function can access all the variables and properties of the outsider function. So, callbacks have access to an outer lexical scope. That means callbacks behave as Closures too.
  3. Higher-Order Functions is the second name of Callback functions because of their behavior, like passing another function as an argument and returning a function as a value from another function.
callbacks in javascript
Callbacks in javascript

In the above figure, we do not always pass the second parameter as a value; I have just taken an example that there have been multiple anonymous functions. Instead, the values can be given the main function and later will execute inside that function. It will always behave as Closures.

If you still have doubts, then ask in the comment below, I am happy to help you.

That’s it for this tutorial.

3 Comments

Leave A Reply

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.