Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"callback" keyword in JavaScript

Please help in understanding the below code:

// define our function with the callback argument

function some_function(arg1, arg2, callback) {
    // this generates a random number between
    // arg1 and arg2

    var my_number = Math.ceil(Math.random() * (arg1 - arg2) + arg2);

    // then we're done, so we'll call the callback and
    // pass our result
    callback(my_number);
}

// call the function
some_function(5, 15, function(num) {
    // this anonymous function will run when the
    // callback is called
    console.log("callback called! " + num);
});

In the above code,what is the callback keyword.what is the use of this word. Even there is no function defined with name callback.

like image 261
user3519807 Avatar asked Sep 30 '15 19:09

user3519807


1 Answers

The gap in logic I think you're having a hard time with is anonymous, unnamed functions. Once upon a time, all functions were named. So code was written like this:

function MemberProcessingFunction() {
  // etc
}

function AdminProcessingFunction() {
  // etc
}

var loginProcessingFunction;

if (usertype == 'BasicMember') {
  loginProcessingFunction = MemberProcessingFunction;
}
else if (usertype == 'Admin') {
  loginProcessingFunction = AdminProcessingFunction;
}
loginProcessingFunction();

Someone thought "This is dumb. I'm only creating those function names to use them in one place in my code. Let's merge that together."

var loginProcessingFunction;

if (usertype == 'BasicMember') {
  loginProcessingFunction = function() {
    // etc
  };
}
else if (usertype == 'Admin') {
  loginProcessingFunction = function() {
    // etc
  };
}
loginProcessingFunction();

This especially saves a lot of time when you're passing a function to another function as an argument. Often, this is used for "callbacks" - occasions where you want to run certain code, but only after a certain indeterminately-timed function has finished its work.

For your top function, callback is the name of the third argument; it expects this to be a function, and it is provided when the method is called. It's not a language keyword - if you did a "find/replace all" of the word "callback" with "batmanvsuperman", it would still work.

like image 152
Katana314 Avatar answered Sep 30 '22 03:09

Katana314