Constructed arrays are enumerable but empty
Array(len)
creates an array and sets its length accordingly but only its length is "enumerable", not the values contained. So, you cannot map the array Array(100).map(/* nope */)
— it's not a "real array" yet and it is actually empty despite having the correct length.
callback is invoked only for indexes of the array which have assigned values including undefined.,
The array
does not contain any values; not even undefined
It is not called for missing elements of the array (that is, indexes that have never been set, which have been deleted or which have never been assigned a value).
To populate array you need to iterate it someway… E.g.: [...Array(100)]
or Array.from(Array(100))
I imagine the purpose of this initialization is to optimize memory allocation… there isn't really anything in the array. MDN says "empty arrayLength
objects" which might be misleading as trying to access any of the "empty items" just returns undefined… But we know they aren't really undefined
since map
fails, therefore we can confirm it is a truly empty array.
Constructor equivalent
This example does not seek to mirror specification but instead to illustrate why an array
returned from Array
cannot yet be iterated
function * (length) {
const arr = [];
Object.defineProperty(arr, 'length', { value: length });
// Equivalent, but invokes assignment trap and mutates array:
// arr.length = length;
Object.defineProperty(arr, Symbol.iterator, {
value() {
let i = 0;
return {
next() {
return {
value: undefined, // (Not omitted for illustration)
done: i++ == length
};
}
}
}
})
return arr;
}
It is worth pointing out that despite providing a undefined
value in the generator value property, it does not recognize it as a value and so the array is empty.
Array(len)
Specification
https://www.ecma-international.org/ecma-262/6.0/#sec-array-len
Array (len) This description applies if and only if the Array
constructor is called with exactly one argument.
1) Let numberOfArgs
be the number of arguments passed to this function
call.
2) Assert: numberOfArgs
= 1.
3) If NewTarget is undefined
, let newTarget
be the active function object, else let newTarget
be NewTarget
.
4) Let proto
be GetPrototypeFromConstructor(newTarget, "%ArrayPrototype%")
.
5) ReturnIfAbrupt(proto)
.
6) Let array be ArrayCreate(0, proto)
.
7) If Type(len
) is not Number, then
a) Let defineStatus
be CreateDataProperty(array, "0", len)
.
b) Assert: defineStatus
is true.
c) Let intLen
be 1.
8) Else, a) Let intLen
be ToUint32(len
). b) If intLen
≠ len
, throw a RangeError exception.
9) Let
setStatus
be Set(array, "length", intLen, true).
10) Assert: setStatus
is not an abrupt completion.
11) Return array.