neverendingqs
neverendingqs

Reputation: 4276

What is the difference between "Array(n)" and "[...Array(n)]"?

What is the difference between the two?

// Chrome console

Array(2);                   // [undefined × 2]
Array(2).map(() => 1);      // [undefined × 2]

[...Array(2)];              // [undefined, undefined]
[...Array(2)].map(() => 1); // [1, 1]

Based on What are Array empty slots?, it seems to be related to memory allocation, but why does the spread operator suddenly cause memory to be allocated in the latter case?

Upvotes: 3

Views: 189

Answers (1)

Karen Grigoryan
Karen Grigoryan

Reputation: 5432

Regarding Array constructor

All these calls are equivalent:

  • Array(2)
  • new Array(2)
  • var a = []; a.length = 2

They are equal in a sense that they allocate memory for assignment, but don't create the indexes.

Object.keys(Array(2)) // [].

That's why when you do

Array(2).map(() => 1); // [undefined × 2]

you essentially change nothing, because no iteration happens over the array, because of lack of iteration index keys that map uses while iterating over the array.

Regarding spread operator

... operator calls the [Symbol.iterator] of an array which is the built in values() iterator and iterates over values even with absent key indexes.

That is why in the outcome we have a new array with distinct undefined values with key indexes in place.

Object.keys([...Array(2)]) // ["0", "1"].

After which map works as expected iterating over the keys and corresponding values.

Upvotes: 6

Related Questions