Skip to content
Advertisement

How does `Array.from({length: 5}, (v, i) => i)` work?

I may be missing something obvious here but could someone breakdown step by step why Array.from({length: 5}, (v, i) => i) returns [0, 1, 2, 3, 4]?

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from

I didn’t understand in detail why this works

Advertisement

Answer

When Javascript checks if a method can be called, it uses duck-typing. That means when you want to call a method foo from some object, which is supposed to be of type bar, then it doesn’t check if this object is really bar but it checks if it has method foo.

So in JS, it’s possible to do the following:

let fakeArray = {length:5};
fakeArray.length //5
let realArray = [1,2,3,4,5];
realArray.length //5

First one is like fake javascript array (which has property length). When Array.from gets a value of property length (5 in this case), then it creates a real array with length 5.

This kind of fakeArray object is often called arrayLike.

The second part is just an arrow function which populates an array with values of indices (second argument).

This technique is very useful for mocking some object for test. For example:

let ourFileReader = {}
ourFileReader.result = "someResult"
//ourFileReader will mock real FileReader
Advertisement