Callbacks

Since functions are objects they can be passed as arguments to other functions.

function test(a, b, fn) {
    fn(a, b);
}

In this simple example we have a function test() that takes a function fn as a third parameter and calls that function passing the first two parameters.

When you cal the test() function, you can pass a pointer to an existing function myFunc() or you can also pass an anonymous function.

test(1, 2, myFunc);
 
test(1, 2, function(one, two){
    console.log(arguments);
});

Examples

For examples of this pattern in the wild well, every time you attach an event listener, you pass a callback function.

document.addEventListener(
    'click', 
    animateAndWowUser, 
    false
);

Same with timeouts and intervals. setTimeout() and setInterval() expect a function and call it back after the specified number of milliseconds.

var thePlotThickens = function(){
  console.log('500ms later...');
};
setTimeout(thePlotThickens, 500);

And here's a common anti-pattern passing a string where a function is expected. The JavaScript engine has no choice but to evaluate the string (like with eval()) and execute it, which is unnecessary work.

// anti-pattern
setTimeout("thePlotThickens()", 500);

Tags: , ,

Sorry, comments disabled and hidden due to excessive spam. Working on restoring the existing comments...

Meanwhile you can find me on twitter - @stoyanstefanov