0

Why does Array(3) return [empty x 3] but [...Array(3)] return [undefined, undefined, undefined].

I was trying to use Array() with map() I had to do the following since map needs initial values

Array(3).fill(0).map(()=>1)
> [1,1,1]

Since the following will not invoke the call back function.

Array(3).map(()=>1)
> [empty × 3]

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

callbackFn is invoked only for array indexes which have assigned values. It is not invoked for empty slots in sparse arrays.

I saw that you can use the spread syntax ... to change the array from no values to an array of undefined values of same length that can then be used to iterate with map.

[...Array(3)].map(()=>1)
> [1, 1, 1]

Why is the spread operator ... creating an array of undefined values? I believe it has to do with the JavaScript iterable protocol but struggling to find the answer.

0 Answers0