2

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.

2
  • What are you confused about? Read up on scoping in Javascript. Commented Aug 9, 2013 at 16:07
  • the second argument to forEach is 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 the total variable which can therefore be used as an accumulator to compute the aggregate sum making it available to the caller without explicit handshake. Commented Aug 9, 2013 at 16:11

4 Answers 4

1

The argument number is passed into the anonymous function which is called for each element in the array. The number argument contains the value of the current array element. The value is added to the global variable total during each iteration, which creates the sum of all the array values. The function then returns total.

Sign up to request clarification or add additional context in comments.

Comments

1

Defining a function inside of another function is called a closure. The inner function has full access to the local variables defined in the outer function.

So when the function used as action in the forEach() call does total += number, this is adding number (the argument) to total (the local variable in sum()). After the forEach() call has completed each number from numbers will have been added to total, and total is returned.

1 Comment

Awesome i get it now! I was looking over the fact that in this situation array[i] = number because thats the parameter that the function is acting on.
0

You are passing numbers as your first param for forEach, so it will go through each elements in that array and then you are doing total += number; which means total = total + number;.

Comments

0

You can checkout how forEach works at MDN

Or implementing it helps a lot in understanding

var each = function(array, func) {
  var aLength = array.length,
    retArr = [],
    i;
  for (i = 0; i < aLength; i++) {
    func(array[i], i, array);
  }
};

function sum(numbers) {
  var total = 0;
  each(numbers, function(number) {
    total += number;
  });
  return total;
}
console.log(sum([1, 10, 100]));

You should also checkout map and reduce

Using reduce for the same task looks as follows

function sum(numbers) {
  return numbers.reduce(function(total, item){
    return total + item;
  });
}
console.log(sum([1, 10, 100]));

Or even without a wrapping function

console.log([1, 10, 100].reduce(function(sum, num) {
  return sum + num;
}));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.