Reputation: 361
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.
Upvotes: 2
Views: 102
Reputation: 2786
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;
}));
Upvotes: 0
Reputation: 4320
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;
.
Upvotes: 0
Reputation: 208405
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.
Upvotes: 1
Reputation: 94429
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
.
Upvotes: 1