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);
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);
Arrow functions introduced in ES6, does not bind its own this. In other words, the context inside arrow functions is lexically or statically defined.
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}