2

Example

Could anyone please tell me why this const is a function? And how is this function used like a map? I was having a hard time understanding this code:

const something = ['a','b','c'].map.bind([1,2,3]);

Thank you 'Euan Smith' for explaining that there are a few ways to get the map - I checked it now: enter image description here

Itay
  • 398
  • 2
  • 14
  • 1
    Because bind returns the same function with new context bound to it... :) – AdityaParab Feb 03 '20 at 09:25
  • What that code means is assuming your original array as `arr`, the prototype method map, that you'd call on it will have the value of `this` set to `[1,2,3]`. When called, it will actually call the map function with the value of `this` as `[1,2,3]` – AdityaParab Feb 03 '20 at 09:27

2 Answers2

2

So first of all the ['a','b','c'] is a distraction. You would get the same overal resul with const something = [].map.bind([1,2,3]);. That first part of the code is just there to get a reference to the map method of an array. The same could be obtained with Array.prototype.map, but [].map takes less typing.

The bind is binding this map function to the array [1,2,3], and that is what something is pointing to, a version of the map function bound to [1,2,3]. For example if you called something(v=>v*2) you would get back [2,4,6].

Check out the MDN pages for Array, Array~map, Function and Function~bind for more info.

Euan Smith
  • 2,102
  • 1
  • 16
  • 26
1

map is function on Array.prototype types assigned on its prototype inheritance structure.

It is just a plain JS function with no object assigned to it. Using bind we are binding the map function to a particular object, here [1,2,3]

paperball
  • 195
  • 1
  • 13