1

Why is this not returning 5? (I think it's returning the global object).

a = [1, 2, 3, 4, 5];

a.forEach(element => {
    console.log(this);
}, 5);
tonitone110
  • 139
  • 6
  • Does this answer your question? [Are 'Arrow Functions' and 'Functions' equivalent / exchangeable?](https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-exchangeable) – VLAZ Jun 27 '20 at 19:19

2 Answers2

4

Arrow functions introduced in ES6, does not bind its own this. In other words, the context inside arrow functions is lexically or statically defined.

Akhil
  • 1,403
  • 7
  • 19
2

Arrow functions do not have their own this, they inherit the one from the parent scope, which is called "lexical scoping", which in your case is global object.

To get 5, you can use normal function instead of arrow funtion

a = [1, 2, 3, 4, 5];

a.forEach(function(element){
    console.log(this);
}, 5);

Output:

Number {5}
Number {5}
Number {5}
Number {5}
Number {5}