top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is callback function in javascript?

0 votes
355 views
What is callback function in javascript?
posted Jul 15, 2014 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

A callback function, also known as a higher-order function, is a function that is passed to another function (let's call this other function “otherFunction”) as a parameter, and the callback function is called (executed) inside otherFunction.

Examples :

function mySandwich(param1, param2, callback) {  
    alert('Started eating my sandwich.\n\nIt has: ' + param1 + ', ' + param2);  
    callback();  
}  

mySandwich('ham', 'cheese', function() {  
    alert('Finished eating my sandwich.');  
});  

Here we have a function called mySandwich and it accepts three parameters. The third parameter is the callback function. When the function executes, it spits out an alert message with the passed values displayed. Then it executes the callback function.

Notice that the actual parameter is just “callback” (without parentheses), but then when the callback is executed, it’s done using parentheses. You can call this parameter whatever you want, I just used “callback” so it’s obvious what’s going on.

The callback function itself is defined in the third argument passed to the function call. That code has another alert message to tell you that the callback code has now executed. You can see in this simple example that an argument passed into a function can be a function itself, and this is what makes callbacks possible in JavaScript.

answer Jul 29, 2014 by Madhavi Latha
...