Emile Paffard-Wray Emile Paffard-Wray - 24 days ago 16
Javascript Question

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

I may be missing something obvious here but could someone breakdown step by step why

Array.from({length: 5}, (v, k) => k)
returns
[0, 1, 2, 3, 4]
?

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

I do't understand in detail why this works

Answer

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

To sum up:

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 checks property length it returns 5 and therefore it creates real array with length 5. You can call fakeArray object "arrayLike".

Second part is just lamba which populates 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
Comments