Callback in Javascript

Like Tweet Pin it Share Share Email
Callback in Javascript

Hey, web geeks, In today’s AppDividend Tutorial, I have briefly described Callback in Javascript.

In Javascript, Functions are objects. They are First Class Objects. 

So, we can use as a variable like Strings and Objects. If they are variables, then we can do 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 that is passed to another function as an argument and the given function is executed inside the otherFunction. That parameterized function is called as Callback. We have used callbacks many times especially in jQuery where we listen from the DOM event and pass the callback to that function. For example

Example #1

//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

1st
2nd
3rd

Memorable Points

  1. One point to remember that we are not executing the function in the parameter, we are only passing the function definition. Parameterized function is executed inside the main function.
  2. If you have read my Closures article, 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 behaves 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, return a function as a value from another function.
callbacks in javascript
Callbacks in javascript

In 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 as well as values can be passed the main function and later it will execute inside that function. It will always behave as a Closures.

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

Comments (0)

Leave a Reply

Your email address will not be published. Required fields are marked *