How does `Array.from({length: 5}, (v, i) => i)` work?
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
var arr1 = Array.from({
length: 5 // Create 5 indexes with undefined values
},
function(v, k) { // Run a map function on said indexes using v(alue)[undefined] and k(ey)[0 to 4]
return k; // Return k(ey) as value for this index
}
);
console.log(arr1);
On developer.mozilla.org page about array.from, nobody tell us that mapFn
can take 2 arguments, for example v
and k
: v
is value of current element, k
is index of element. So here's the deal.
{length:5}
create an object without any value, but with length
equal to 5
;
(v, k) => k
is an arrow function that assign index number of current element to that element value.