AppDividend
Latest Code Tutorials

Callback in Javascript

391

Get real time updates directly on you device, subscribe now.

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

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. In this example, click function’s argument is another function. So that another function is a callback. Wherever click event happens 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 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 arrow function which is new ES6 feature in Javascript 

If you directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  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 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 above example, first of all, we have 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 that 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 above example, we have used the setTimeout event, which is Asynchronous and entirely dependent on a specified time interval. Here in also the setTimeout event accepts two parameters

Related Posts
1 of 5
  1. Anonymous Function
  2. Time(milliseconds)

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

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.

2 Comments
  1. Naimish says

    Awesome website….

    1. Krunal says

      Thanks, buddy!!

Leave A Reply

Your email address will not be published.

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