Defining arrays in javascript using Array(n) defines an empty array, please correct me if I am wrong. Now if I write the below code:
Array(2).map((val) => console.log(val))
.. nothing happens, but when I spread out the elements of the array into an other array, like so:
[...Array(2)].map((val) => console.log(val))
.. I get undefined console logs. Can anyone please help me understand what is happening here ?
Without spreading, the array is simply an object with a length property, with no items populated:
{ length: 2, proto: Array(0) }
When you spread (...) into an array, if the object you're spreading has a length property, it will spread that many items, starting from obj[0], obj[1], etc. The object in question doesn't actually need to have those numeric properties - if it doesn't, then the result of the spreading will be an array of undefineds:
console.log([...Array(2)]);
An array of undefineds can be iterated over - here, the indicies 0 and 1 do exist in the array object, they just happen to not be assigned to anything.
const arr = [undefined, undefined];
console.log(1 in arr);
So, in short, it's because the difference between an array such as
{ length: 2 } // no elements to iterate over
and
{ length: 2, 0: undefined, 1: undefined }
Note that you shouldn't use map if you're not using the transformed array that .map returns - otherwise, if you just want to iterate over each item and console.log it, for example, you should use forEach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With