Okay I understand that in the forEach function the action parameter is acting as the print function and being called on each element in the array for the following Code Below:
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
forEach(["Wampeter", "Foma", "Granfalloon"], print);
But in the next example a function definition is being passed in place of the action parameter for forEach as follows:
function sum(numbers) {
var total = 0;
forEach(numbers, function (number) {
total += number;
});
return total;
}
show(sum([1, 10, 100]));
Which I am lost at. This code some how prints out the sum of a given array but I can not explain how it does it or how it works. Question 1: How or when is number given a value since it is local and used to give total its final value? Question 2: How is total += number acting on each element in the array.
forEachis a function object which is called on each element of the Array with the respective array element as an argument. the function object actually is a closure, meaning that it implicitly receives access to (part of) the environment at the definition location: in this case, it's thetotalvariable which can therefore be used as an accumulator to compute the aggregatesummaking it available to the caller without explicit handshake.