When an array is not spread, it remains as an object with only a length
property and no populated items:
{ length: 2, proto: Array(0) }
However, when you use spread operator (...
) on an array, it will populate the array with items based on the original object’s properties starting from obj[0]
, obj[1]
, etc. If the object does not have these numeric properties, the result of spreading will create an array filled with undefined
s:
console.log([...Array(2)]);
An array of undefined
s can still be iterated over – even though the values are not assigned to anything:
const arr = [undefined, undefined];
console.log(1 in arr);
Therefore, the distinction lies between an array like
{ length: 2 } // no elements to iterate over
and
{ length: 2, 0: undefined, 1: undefined }
It's important to choose the correct array method for your task - if you simply need to loop through each item without transforming them, consider using forEach
instead of map
.