I want to create empty array with fixed length, and then use .map on it to return new array. However, it's not working as expected.
According to mdn docs:
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) returns [undefined × 3]. Shouldn't it be: [undefined, undefined, undefined]?
Let's consider following examples:
1) Not working.
var a = new Array(3);
a.map((x, i) => i); // [undefined × 3]
2) Working.
var a = Array.apply(null, new Array(3));
a.map((x, i) => i); // [0, 1, 2]
I tested this on latest Google Chrome Canary.
[undefined × 3]Array [ <3 empty slots> ]in Firefox. The more you know.new Array(3)does not create an array with elements, its only a dummynew Array(3)creates an empty array (all indices are not defined) where only thelengthproperty is set to3.Array.apply(null, new Array(3))is the same asnew Array(undefined, undefined, undefined)which creates an array of length 3 where each index has the valueundefinednew Array(3)has different output than settinglength = 3on an empty array. (But results in having the same properties on closer inspection fiddle)