Trying to allocate new array with values.
Case 1 :
var x = new Array(3).map(()=>1);
Now x
is [undefined * 3]
Case2 :
var x = [...new Array(3)].map(()=>1);
And now x
is [1,1,1]
Can someone help here?
Why using this spread operator makes such a difference?
And why Case 1 doesn't work ?
tl;dr: The first array has holes, the second one doesn't. .map
skips holes.
By using a spread element, the array is treated as an iterable, i.e. you get an iterator to iterate over the array. The iterator basically works like a for
loop, it will iterate the array from index 0
to index array.length - 1
(see the spec for details), and add the value at each index to the new array. Since your array doesn't contain any values, array[i]
will return undefined
for every index.
That means, [...new Array(3)]
results in an array that literally contains three undefined
values, as opposed to just a "spare" array of length 3
.
See the difference in Chrome:
We call "sparse arrays" also "arrays with holes".
Here is the crux: Many array methods, including .map
, skip holes! They are not treating the hole as the value undefined
, the completely ignore it.
You can easily verify that by putting a console.log
in the .map
callback:
Array(3).map(() => console.log('call me'));
// no output
And that's the reason your first example doesn't work. You have a sparse array with only holes, which .map
ignores. Creating a new array with the spread element creates an array without holes, hence .map
works.
Array
arrayLength
If the only argument passed to the
Array
constructor is an integer between 0 and 232-1 (inclusive), this returns a new JavaScript array with length set to that number.
new Array(3)
does not actually create iterable values at created array having .length
property set to 3
.
See also Undefined values with new Array() in JavaScript .
You can use Array.from()
at first example to return expected results
var x = Array.from(Array(3)).map(()=>1);
Spread operator
The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) or multiple variables (for destructuring assignment) are expected.
var x = [...new Array(10)].map(()=>1);
creates an array having values undefined
and .length
set to 10
from Array(10)
, which is iterable at .map()
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