2

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?

extensa5620
  • 681
  • 2
  • 8
  • 22

3 Answers3

5

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");

See it in action.

Finally, you would likely benefit from examining how callbacks work and what their uses are; here is another answer of mine on this subject.

Community
  • 1
  • 1
Jon
  • 428,835
  • 81
  • 738
  • 806
  • @Alnitak: It is the source for the `forEach` that the question talks about, not `Array.forEach`. – Jon May 30 '13 at 08:12
  • ah, ok, not the standard one :) I suggest OP would be better off learning how standard ES5 methods support these features, rather than following what appears to be an out-of-date website. – Alnitak May 30 '13 at 08:13
  • @user2135737 I think the concept to grasp here in order to understand JS better, other than the code, is "first class" and "higher order" functions. AFAIK Java doesn't have this (at least not in the same way) because it's not a functional language. – elclanrs May 30 '13 at 08:14
2

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.

Jakob
  • 751
  • 4
  • 17
1

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.

Yevgeny Simkin
  • 27,946
  • 39
  • 137
  • 236