Why do I need to copy an array to use a method on it?
When you use Array(arrayLength)
to create an array, you will have:
a new JavaScript array with its length property set to that number (Note: this implies an array of arrayLength empty slots, not slots with actual undefined values).
The array does not actually contain any values, not even undefined
values - it simply has a length
property.
When you spread an iterable object with a length
property into an array, spread syntax accesses each index and sets the value at that index in the new array. For example:
const arr1 = [];
arr1.length = 4;
// arr1 does not actually have any index properties:
console.log('1' in arr1);
const arr2 = [...arr1];
console.log(arr2);
console.log('2' in arr2);
And .map
only maps properties/values for which the property actually exists in the array you're mapping over.
Using the array constructor is confusing. I would suggest using Array.from
instead, when creating arrays from scratch - you can pass it an object with a length
property, as well as a mapping function:
const arr = Array.from(
{ length: 2 },
() => 'foo'
);
console.log(arr);
As pointed out by @CertainPerformance, your array doesn't have any properties besides its length
, you can verify that with this line: new Array(1).hasOwnProperty(0)
, which returns false
.
Looking at 15.4.4.19 Array.prototype.map you can see, at 7.3, there's a check whether a key exists in the array.
1..6. [...]
7. Repeat,
while k < len
Let Pk be ToString(k).
Let kPresent be the result of calling the [[HasProperty]] internal method of O with argument Pk.
-
If
kPresent is true, then
Let kValue be the result of calling the [[Get]] internal method of O with argument Pk.
Let mappedValue be the result of calling the [[Call]] internal method of callbackfn with T as the this value and argument list containing kValue, k, and O.
Call the [[DefineOwnProperty]] internal method of A with arguments Pk, Property Descriptor {[[Value]]: mappedValue, [[Writable]]: true, [[Enumerable]]: true, [[Configurable]]: true}, and false.
Increase k by 1.
The reason is that the array element is unassigned. See here the first paragraph of the description. ... callback is invoked only for indexes of the array which have assigned values, including undefined.
Consider:
var array1 = Array(2);
array1[0] = undefined;
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(array1);
console.log(map1);
Outputs:
Array [undefined, undefined]
Array [NaN, undefined]
When the array is printed each of its elements are interrogated. The first has been assigned undefined
the other is defaulted to undefined
.
The mapping operation calls the mapping operation for the first element because it has been defined (through assignment). It does not call the mapping operation for the second argument, and simply passes out undefined
.