I think you're not grasping the syntactic structure of the call. One could equally write
var numbers = [1, 2, 3, 4, 5];
var sum = 0;
function addToSum(number) {
sum += number;
}
forEach(numbers, addToSum);
I hope it is clear what is happening in here. We have a function addToSum
, and pass that function to the forEach
function - where we refer to it by its parameter name action
, and will call it with each element of the passed array in the body of the loop: action(array[i])
. The great deal about this abstraction is that we can pass any arbitrary function to forEach
…
So what is this odd syntax now? First, it is replacing the function declaration by a function expression. A function expression is just an expression that evaluates to a function object, just as the array literal [1, 2, 3, 4, 5]
evaluates to the array object. It's also called an anonymous function as it does not have a name. We take this value and assign it to a variable:
var numbers = [1, 2, 3, 4, 5];
var sum = 0;
var addTosum = function(number) {
sum += number;
}
forEach(numbers, addToSum);
Nothing has really changed until here. Now, why would we need that variable? We don't really need those identifiers pointing to the values that we created with the expressions. We now just put the expressions directly in the forEach
function call - still passing the same values (forEach
does not spot a difference):
var sum = 0;
forEach([1, 2, 3, 4, 5], function(number) {
sum += number;
});