Reputation: 41
I'm learning JavaScript now. And I have some question. The following code from the book Eloquent JavaScript:
function forEach(array, action) {
for (var i = 0; i < array.length; i++)
action(array[i]);
}
var numbers = [1, 2, 3, 4, 5],
sum = 0;
forEach(numbers, function(number) {
sum += number;
});
console.log(sum);
What is happening in this code? How does the forEach function, when called, determine what is the number? How does it extract number from the numbers array?
Upvotes: 1
Views: 160
Reputation: 707258
What is happening in this code?
Here's a description of how your forEach
function works:
forEach
function accepts two arguments, the array and a functionfor
loop to iterate through the arrayaction(array[i])
which calls the passed in function and passes it one array element. array[i]
gets the next item from the array and action(array[i])
calls the passed in function and passes it that next item from the array.Then, when you call it like this:
forEach(numbers, function(number) {
sum += number;
});
It will call the function you passed it once for each number in the numbers
array and when it calls that function, it passed a number from the array as the first argument to your function.
One thing that confuses some people is the number
argument in your function you are passing to forEach
is just a name you assign to the first argument of the function. It can be named anything you want and has nothing to do with any names used in the forEach()
function definition. The declaration of arguments for functions are just labels assigned to each argument which make it easier for you to use them. You could have also done this:
forEach(numbers, function(whateverYouWant) {
sum += whateverYouWant;
});
How does the forEach function, when called, determine what is the number?
Your for
loop iterates through the whole array one number at a time and calls the callback function once for each number in the array.
How does it extract number from the numbers array?
array[i]
is where a number is extracted from the array. This is normal array indexing for retrieving the i th value from the array where i
varies from 0
to the length of the array minus 1.
Upvotes: 5