I am confused by the results of mapping over an array created with new:
function returnsFourteen() {
return 14;
}
var a = new Array(4);
> [undefined x 4] in Chrome, [, , , ,] in Firefox
a.map(returnsFourteen);
> [undefined x 4] in Chrome, [, , , ,] in Firefox
var b = [undefined, undefined, undefined, undefined];
> [undefined, undefined, undefined, undefined]
b.map(returnsFourteen);
> [14, 14, 14, 14]
I expected a.map(returnsFourteen) to return [14, 14, 14, 14] (the same as b.map(returnsFourteen), because according to the MDN page on arrays:
If the only argument passed to the Array constructor is an integer
between 0 and 2**32-1 (inclusive), a new JavaScript array is created
with that number of elements.
I interpret that to mean that a should have 4 elements.
What am I missing here?
When you create an array like so:
you get an array that has a length of
4, but that has no elements. That’s whymapdoesn’t tranform the array – the array has no elements to be transformed.On the other hand, if you do:
you get and array that also has a length of
4, but that does have 4 elements.Notice the difference between having no elements, and having elements which values are
undefined. Unfortunately, the property accessor expression will evaluate to theundefinedvalue in both cases, so:However, there is a way to differentiate these two arrays: