Emile Paffard-Wray Emile Paffard-Wray - 1 year ago 102
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)
[0, 1, 2, 3, 4]


I do't understand in detail why this works

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download