Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

passing thisArg to a map function [duplicate]

Tags:

javascript

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?

like image 559
edkeveked Avatar asked Dec 05 '25 14:12

edkeveked


1 Answers

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.

like image 84
Barmar Avatar answered Dec 07 '25 03:12

Barmar