arrayCalc
function takes two parameters:
arr
- Array you want to do calculation on
fn
- This is another function representing the calculation you want to do on elements of the arr
. It is ussualy refered to as callback function
callback function
is function that you send as a argument to another function. In your case main function is arrayCalc
and callback function
is calculateAge
Main function ussually invokes(uses) callback function on the other parameter. That would be array years
in your example.
So your main function
goes trought elements of you array and invokes callback funcion
with that element as a argument and save result to the new array that is then returned from your 'main function'
I will try to make it more clear by rewording your example:
function arrayCalc(parameterArray, parameterCallbackFunction) {
// create new array for results of calling callback
var newArray = [];
// goes trough the array
for (var indexOfElement = 0; indexOfElement < parameterArray.length; indexOfElement++) {
// this is callbackFunction invocation with element of array as argument: parameterCallbackFunction(parameterArray[indexOfElement])
// and we put the resul to the newArray by push method
newArray.push(parameterCallbackFunction(parameterArray[indexOfElement]));
}
// at the end we return newArray filled with results of calling callbackFunction on array
return newArray;
}
// this is array we want to change using callbackFunction
var argumentArray = [1990, 1965, 1937];
// this is our callback function
function argumentCallbackFunction(elementFromArray) {
return 2017 - elementFromArray;
}
// this is invocation of our main function
// first parameter is array and second is our callback function
var ages = arrayCalc(argumentArray, argumentCallbackFunction);
console.log(ages);
You can create many more callback function and use them in arrayCalc
// this is second callbackFunction
function addTenToYear(elementFromArray) {
return elementFromArray + 10;
}
// invocation arrayCalc with second callback function
var agesAfterAddition = arrayCalc(originalArray, addTenToYear);
console.log(agesAfterAddition); // [2000, 1975, 1947]
// this is third callbackFunction
function substractTenFromYear(elementFromArray) {
return elementFromArray - 10;
}
// invocation arrayCalc with third callback function
var agesAfterSubstraction = arrayCalc(originalArray, substractTenFromYear);
console.log(agesAfterSubstraction); // [1980, 1955, 1927]
Something like this is going on in your code:
var originalArray = [1990, 1965, 1937]
var newArray = []
newArray.push( callbackFunction(1990) ) // 2017 - 1990 = 27
console.log(newArray) // [27]
newArray.push( callbackFunction(1965) ) // 2017 - 1965 = 52
console.log(newArray) // [27, 52]
newArray.push( callbackFunction(1937) ) // 2017 - 1937 = 80
console.log(newArray) // [27, 52, 80]