I am having trouble trying to understand the code below. I'm coming from a Java background. How should I read this? Is there any good Java > Javascript books/tutorials I should be looking at?
function sum(numbers) {
var total = 0;
forEach(numbers, function (number) {
total += number;
});
return total;
}
show(sum([1, 10, 100]));
Extracted from http://eloquentjavascript.net/chapter6.html
I'm looking at the forEach(numbers, function (number)... code. Where will the anonymous function get the 'number' from?
3 Answers 3
Look at the source of forEach:
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
forEach accepts two arguments: an array and a callback (i.e. a function). You can see that it invokes the callback in a loop, passing it the "current" array element as an argument each time. That's what goes into the formal parameter number of the callback.
To put this another way -- you can easily understand this:
function hello(what) {
alert("Hello " + what);
}
hello("world");
If you use hello as a callback you arrive at code much like the one you show:
function say(callback, what) {
callback(what);
}
say(hello, "world");
Finally, you would likely benefit from examining how callbacks work and what their uses are; here is another answer of mine on this subject.
3 Comments
forEach that the question talks about, not Array.forEach.It gets the number from numbers. What the foreach says is that for each element in numbers call the anonymous function with that element. Then that element is called number but it could be called anything.
Comments
What you're being confused by is that you're not seeing the underlying mechanism of forEach... if you were to pry it open you'd see that that function expects an anonymous function as its second parameter, and it will pass whatever it needs to into IT. So you can expect that parm to be populated when you run your function. It's definitely jarring when you come at it from a different language, but you have to trust that things work the way they're designed to work.