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

2
  • 1
    Because bind returns the same function with new context bound to it... :) Commented Feb 3, 2020 at 9: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] Commented Feb 3, 2020 at 9:27

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.