Creating array with spread operator

Viewed 1108

Here is a javascript arrow function I found in a React book:

const createArray = (length) => [...Array(length)];

Why not simply return a new array?

const createArray = (length) => Array(length);

If I log the result of createArray(7) with either of the definitions, I get the same result:

(7) [undefined, undefined, undefined, undefined, undefined, undefined, undefined]

What does the first definition achieve as compared to the second one?

3 Answers

Both ways of creating an array are different. They do not produce the same result.

Second way of creating an array will create a sparse array with only length own property and no index properties. You can see this using Object.getOwnPropertyNames()

const arr = new Array(5);
console.log(Object.getOwnPropertyNames(arr));

Using the spread syntax will create an array will index properties as shown in the following code example:

const arr = [...new Array(5)];
console.log(Object.getOwnPropertyNames(arr));

Array(length); will create a sparse array - one with no own-properties (except length), which cannot be iterated over with the array iteration methods:

const arr = new Array(7);

console.log(arr.hasOwnProperty('4'));
arr.forEach(() => {
  console.log('iteration');
});

In contrast, utilizing spread syntax will populate the new array properly:

const arr = [...new Array(7)];

console.log(arr.hasOwnProperty('4'));
arr.forEach(() => {
  console.log('iteration');
});

Related