I am learning JS and was trying to understand callbacks. I came across a link: How to explain callbacks in plain english? How are they different from calling one function from another function? In the accepted answer the solution using callbacks is as follows:
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;});
alert(arrReturned);
However when I tried doing the same thing without using callbacks as follows, I got the same answer as above.
function processArray2(arr) {
var resultArr = new Array();
for(var i = arr.length-1; i >= 0; i--)
resultArr[i] = negate(arr[i]);
return resultArr;
}
function negate(n) {
return n*-1;
}
var arr = [1, 2, 3, 4];
var arrReturned2 = processArray2(arr);
alert(arrReturned2);
When the same thing can be done without callbacks why do we need to use callback in the above example. I know I am definitely missing something. But I can't seem to understand what.