new Array(3)returns an array of length 3 containing 3 undefineds which is equivalent to [undefined, undefined, undefined];
However,
[undefined, undefined, undefined].map((val, i) => i) produces the expected result of [0, 1, 2]. But new Array(3).map((val, i) => i) produces [undefined, undefined, undefined], as if the map function had not effect whatsoever.
Could anyone explain why?
EDIT
Looks like there is a flaw in my understanding of new Array(). It does NOT create a new array. It creates an object with key length equal to the argument passed in. Thanks for the answers and comments.
Btw if you do need an array like [undefined, undefined, undefined] to iterate/map over, or for anything then [...new Array(m)] should do the trick.
lengthproperty. In the case ofnew Array(3), you generate anArrayobject with itslengthset to 3, but none of the numeric properties. You can see this: > Object.keys( new Array( 3 ) ); [] > Object.keys( [ undefined, undefined, undefined] ); ["0", "1", "2"] You can achieve what you want withArray.from: > Object.keys( Array.from( { length: 3 } ) ); ["0", "1", "2"]