If you've never worked with callbacks before, you might find the concept a little puzzling. This is especially true in JavaScript, given the several different ways that JavaScript allows you to declare functions.
A callback()
function is used for passing to other functions for them to use. It's a way to pass logic just as you would pass an object:
var myArray = [1,2,3]; function myCallback(x){return x+1}; console.log(myArray.map(myCallback));
To make it simpler for easy tasks, anonymous functions can be used:
console.log(myArray.map(function(x){return x+1}));
They are not only used in functional programming, they are used for many things in JavaScript. Purely for example, here's a callback()
function used in an AJAX call made with jQuery:
function myCallback(xhr){ console.log(xhr.status); return true; } $.ajax(myURI).done(myCallback);
Notice that only the name of the function was used. And because we're not calling the callback and are only passing the name of it, it would be wrong to write this:
$.ajax(myURI).fail(myCallback(xhr)); // or $.ajax(myURI).fail(myCallback());
What would happen if we did call the callback? In that case, the myCallback(xhr)
method would try to execute—'undefined' would be printed to the console and it would return True
. When the ajax()
call completes, it will have 'true' as the name of the callback function to use, and that will throw an error.
What this also means is that we cannot specify what arguments are passed to the callback functions. If we need different parameters from what the ajax()
call will pass to it, we can wrap the callback function in an anonymous function:
function myCallback(status){ console.log(status); return true; } $.ajax(myURI).done(function(xhr){myCallback(xhr.status)});