Reputation: 5849
I am unable to clearly understand the usage of the arguments of forEach()
in javascript.
( I understand the first one is the function which will be called on each element of the array. )
Here are my questions:
1) What is the second argument used for? Can anyone give an example?
2) Does the function (the first argument) always have 3 arguments: entry, index and array?
3) Also some websites explain Array.prototype.forEach()
. Is this the same forEach()
or is this anything different?
Here is my jsfiddle.
I tried in vain to search online for a simple explanation! Thanks for the help.
Upvotes: 3
Views: 115
Reputation: 18462
The second argument is used to set this
in the function context. An example:
var person = {
name: 'Bob',
age: 30
};
var arr = ["foo", "moo", "koo"];
arr.forEach(function(entry, index, array) {
console.log(this.name + ' says ' + entry);
}, person);
You will always get all 3 of those, but you don't need to reference them if you don't need them.
Upvotes: 3
Reputation: 29073
1) the second arg to forEach lets you control that the 'this' variable represents inside the function that you passed into the first parameter of forEach
2) your function will always be passed those 3 args but you can define your function with only the first arg or the first two args if those are all you need
3) yes when people talk about forEach, they are technically referring to Array.prototype.forEach(). (in your jsfiddle, you are calling forEach on an array object)
Upvotes: 0