0

In below code:

var x = 10;

var arr = [1,2,3];

arr.forEach(function(arr){
  this.x = 100;
});
console.log(x); // prints '10'
console.log(this.x); //  prints 'undefined'

arr.forEach( elm =>{
  this.x = 200; 
});
console.log(x); // prints '10'
console.log(this.x); // prints '200'

Can anyone please explain why it's happening?

Thanx in advance

Rahul Munjal
  • 1,926
  • 2
  • 12
  • 27
  • in what environment are you running that code? browser? – Adelin Feb 13 '19 at 07:45
  • [Javascript ES6 — Arrow Functions and Lexical `this`](https://hackernoon.com/javascript-es6-arrow-functions-and-lexical-this-f2a3e2a5e8c4) – undefined Feb 13 '19 at 07:46
  • There's no `this` in arrow functions. So it's just `x` what is assigned. BTW your results are inaccurate it's 100, 100, 200, 200 there's no result of 10. – zer00ne Feb 13 '19 at 07:46
  • 1
    in most cases, `this.x === x` at the global level – Adelin Feb 13 '19 at 07:46
  • @zer00ne- The outputs are from the console that I tested by creating a JS file and running the file via node. i.e. 'node test.js'. While running the code in the browser, the output is '10,100,10,200' respectively. – Rahul Munjal Feb 13 '19 at 09:06
  • While running in the browser, the output is '10,100,10,200' respectively While using 'let' keyword and yes '100,100,200,200' with 'var' keyword. – Rahul Munjal Feb 13 '19 at 09:10

0 Answers0