I'm having trouble understanding the mechanics of this code. Here's what I've got:
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action (array[i]);
}
var numbers = [1, 2, 3, 4, 5], sum = 0;
forEach(numbers, function(number) {
sum += number;
});
console.log(sum);
I can see that sum =+ number;
is passed to forEach
, iterating through the array numbers. However, I'm struggling with the specifics of how this process unfolds. Substituting function(number) {sum =+ number}
in place of action
like this:
for (var i = 0; i < [1, 2, 3, 4, 5].length; i++)
function(number) {
sum += number;
} (array[i]);
}
doesn't make sense, and it doesn't execute properly. The following does work:
var numbers = [1, 2, 3, 4, 5], sum = 0;
for (var i = 0; i < numbers.length; i++)
sum += (numbers[i]);
debug(sum);
console.log(sum);
This version is more concise and functional but I'm still trying to grasp the underlying principles. How do you arrive at this point? Essentially, what is happening behind the scenes?
Any assistance on clarifying this would be greatly appreciated. This topic appears fundamental to Haverbeke's methodology, so understanding it thoroughly is crucial.