correct usage of JavaScript forEach

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?

  • Javascript associative array modification during for loop
  • thisArg of array.forEach does not reference as expected
  • How do I convert a JavaScript forEach loop/function to CoffeeScript
  • JavaScript alternative to “for each” loop
  • how to Use <c:forEach> in scripts tag on JSP page?
  • forEach over es6 Map in JSX
  • Here is my jsfiddle.

    I tried in vain to search online for a simple explanation! Thanks for the help.

  • Enhanced for loop in 2D Array - JavaScript
  • Using js forEach with a nodeList
  • How i can pass an extra parameter via the function used by the Array.forEach method?
  • Can't get this reduce function to work
  • How to return from forEach leaving the embracing method?
  • for iteration, element is undefined
  • 2 Solutions collect form web for “correct usage of JavaScript forEach”

    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( + ' 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.

    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)