How to explain callbacks in plain English? How are they different from calling one function from another function taking some context from the calling function? How can their power be explained to a novice programmer?
Answer
Often an application needs to execute different functions based upon its context/state. For this, we use a variable where we would store the information about the function to be called. According to its need the application will set this variable with the information about function to be called and will call the function using the same variable.
In javascript, the example is below. Here we use method argument as a variable where we store information about function.
function processArray(arr, callback) {
var resultArr = new Array();
for (var i = arr.length-1; i >= 0; i--)
resultArr[i] = callback(arr[i]);
return resultArr;
}
var arr = [1, 2, 3, 4];
var arrReturned = processArray(arr, function(arg) {return arg * -1;});
// arrReturned would be [-1, -2, -3, -4]
No comments:
Post a Comment