When you creating empty array that have a length, all slots are unassigned, they don't even have undefined
value. Map on
the other hand, can only iterate thru assigned values.
Good explanation is on developer.mozilla.org
MDN Array()->Parameters->arrayLength
(...) Note: this implies an array of arrayLength empty slots, not slots with actual undefined values (...)
MDN map()->description
(...) callback is invoked only for indexes of the array which have assigned values (...)
This is why on Array(3).map(_=>1)
, map()
callback have no effect.
Second part is how spread is working. When you are spreading array with 3 empty slots, you are creating new array, that have
filled slots. Now you have all slots with value undefined. From now, map will work as expected.
Examples:
Welcome to Node.js v12.20.1.
Type ".help" for more information.
> Array(3)
[ <3 empty items> ]
> [...Array(3)]
[ undefined, undefined, undefined ]
> const a = []
> a.length = 2
> a
[ <2 empty items> ]
> [...a]
[ undefined, undefined ]