Search code examples
javascriptfirst-class-functions

JS :: First Class Functions :: Parameter Value Confusion


I do not understand how the parameter of the first class function, "number", has the value it does.

I have been mulling over this problem for a couple of days and I am not making any progress in my thinking. There is no error code as this is perfectly valid JS.

This example code is from the book Eloquent JS (http://eloquentjavascript.net/2nd_edition/05_higher_order.html#c_chCFkdNvRH 2nd ed).

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

//vars
var numbers = [1, 2, 3, 4, 5], sum = 0;

// implemented function
forEach(numbers, function(number) {
  sum += number;
});

//output
console.log(sum);
// → 15

I dont understand why 'number' is not considered undefined. Shouldn't the parameter be 'numbers[i]' or 'numbers', which references the actual array?


Solution

  • In the forEach declaration you are passing a function reference as a second argument which you are calling and passing a value from the array:

    function forEach(array, action) <--- action is a function reference
    

    action is called like action(array[i]), with a value from array.

    Now when forEach is called the value for the action is an actual function object.

    You can visualize it as such:

    action = function(number) {
      sum += number;
    }
    

    action is expected to take a argument which is called with a value from an array, so the number parameter is actually that value from the array array[i]