0

I need help breaking down line by line what happens in this example (an excerpt from Eloquent Javascript):

We have the forEach function which logs every item in an array. I understand how that works.

function forEach(array, action) {
  for (var i = 0; i < array.length; i++)
  action(array[i]);
}

So we have an array called 'numbers' and another variable called 'sum' set to 0. Where I get lost is when 'function(number)' gets passed into the the action parameter. What does that do and how does it work? I don't see what it's value is. Can someone break this down?

var numbers = [1, 2, 3, 4, 5], sum = 0;
forEach(numbers, function(number) {
  sum += number;
});

console.log(sum);
// → 15

1 Answers1

0

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;
});
Community
  • 1
  • 1
Bergi
  • 630,263
  • 148
  • 957
  • 1,375