2

This question might already be asked. From the documentation, we can pass a thisVariable to a map function.

var foo=[1,2].map(function(){return this.length},[2,4]); // [2,2]

This syntax in ES6, however, returns something else

var foo=[1,2].map(_ => this.length ,[2,4]); // [0,0]

What is the [0,0] returned?

edkeveked
  • 17,989
  • 10
  • 55
  • 93
  • 6
    That is because you're using an arrow function `.. => ...` which preserves the context. – Titus Jan 04 '18 at 00:22
  • Per MDN: An arrow function expression has a shorter syntax than a function expression and does not have its own `this`, `arguments`, `super`, or `new.target`. These function expressions are best suited for non-method functions, and they cannot be used as constructors. – Tareq Jan 04 '18 at 00:28
  • @Titus, I understand that it is related to the fact that `=>` preserves the context. Having said that, does it mean that we cannot achieve the same result with the arrow function ? – edkeveked Jan 04 '18 at 00:30
  • yes. in `map` fun. the second param is `this` value which arrow function will not recognize anyway. to be able to use it, try normal function or function expressions – Tareq Jan 04 '18 at 00:32
  • 1
    @edkeveked Correct, if you want to set the context (to set `this`), you'll need to use a normal function. – Titus Jan 04 '18 at 00:34
  • note: should use `let` instead `var` – Chase Choi Jan 04 '18 at 00:39

1 Answers1

6

An arrow function retains the thisValue that was in scope in the calling function, it can't be reset. So the thisValue argument passed to map() is ignored.

So when your uses this.length, it's using the value of this from the calling context. If you're executing the code at top level (e.g. in the Javascript console), this == window, so you're getting the result of window.length, which is 0.

Barmar
  • 741,623
  • 53
  • 500
  • 612