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);

Leave a Comment