5

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
  • 4
    Array(5) => [empty x 5] vs. [...Array(5)] => [undefined, undefined, undefined, undefined, undefined]. The difference is initialisation. Commented Feb 6, 2021 at 14:26
  • In which environment you're getting the same result? Commented Feb 6, 2021 at 14:29
  • Using code sandbox Commented Feb 6, 2021 at 15:14

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

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

1 Comment

Thanks. This helped. I could quickly change the log statement to dump getOwnPropertyNames() and it showed the first method giving all the index properties along with length property whereas the second one only dumped the length property
-1

i hope if you want its example here.

More Information = > https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

const testArr = [
        { name: false, expected: false },
        { name: null, expected: false },
        { name: undefined, expected: false },
        { name: "", expected: false },
        { name: "  \t\n", expected: false },
    ];
    
    const createArray = (arr) => { return [...arr]}
    
    console.log(createArray(testArr))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.