1

I extremely confusing In forEach loop why the THIS will point to the obj.

I assume will output return this.id is undefined , because it called in a lexical function. THIS will point it to window.

function foo(el) {
  console.log( el, this.id);
}

 var obj = {
   id: "awesome"
 };

 [1, 2, 3].forEach( foo, obj );
 // 1 "awesome" 2 "awesome" 3 "awesome"


 // Easy way to check
 [1, 2, 3].forEach( function(el){
   console.log( el, this.id);
 }, obj);
Wilker
  • 551
  • 2
  • 6
  • 21
  • 2
    You explicitly told it to use `obj` as `this`. That's what the second argument to `forEach` is *for*. – user2357112 Dec 14 '19 at 06:20
  • Inside forEach method, the second parameter should for Index of the array. Why Object variable able to use in the second parameter? – Wilker Dec 14 '19 at 06:24
  • 2
    Please see forEach syantax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach The first argument is callback function and second param is value of this while executing callback. – Abhishek Dec 14 '19 at 06:24
  • Great. Sharing the forEach syntax rule. – Wilker Dec 14 '19 at 06:26

1 Answers1

1

The second argument to Array.prototype.forEach is the thisArg. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach which states:

If a thisArg parameter is provided to forEach(), it will be used as callback's this value.

Matt U
  • 4,970
  • 9
  • 28