3

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.

2 Answers 2

3
  1. 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);
    
  2. You will always get all 3 of those, but you don't need to reference them if you don't need them.

  3. They are the same.
Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.