#50: Array.from({ length: 3 })
Topic: arrays · Difficulty: ★
console.log(Array.from({ length: 3 }));
console.log(Array.from({ length: 3 }, (_, i) => i));Output
[ undefined, undefined, undefined ] [ 0, 1, 2 ]
Why
Array.from() can build an array from any 'array-like' object — anything with a numeric length property, even one with no indexed values at all. Given just { length: 3 }, it creates a real, dense array of length 3 whose slots are actual undefined values (unlike the holes from Array(3)), because Array.from always visits every index up to length. Passing a second mapping-function argument runs that function on each index during construction, so (_, i) => i fills the array with its own indices, [0, 1, 2] — a common idiom for generating numeric ranges without a for loop.