Why do I need to copy an array to use a method on it?

  • A+

I can use Array() to have an array with a fixed number of undefined entries. For example

Array(2); // [empty × 2]  

But if I go and use the map method, say, on my new array, the entries are still undefined:

Array(2).map( () => "foo");  // [empty × 2]  

If I copy the array then map does work:

[...Array(2)].map( () => "foo");  // ["foo", "foo"] 

Why do I need a copy to use the array?


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 item with a length property into an array, eg [...{ length: 4 }], 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);


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: