0

To create an array of x elements in length where all elements are undefined to begin with, I use the Array(x) function. If I enter this into the Chrome devtools console, it is displayed in a shorthand notation like this:

undefined x 6

If I then use the spread operator (...) to shallow-copy this array, the representation changes to a full array printout:

undefined, undefined, undefined, undefined, undefined, undefined

If I manually enter the array, the full printout is also used:

undefined, undefined, undefined, undefined, undefined, undefined

Why is this? What are the conditions for Chrome's undefined × x shorthand to be used?

Edit

Using the new keyword before creating the array of undefineds does not make a difference to Chrome's representation:

enter image description here

Aaron Christiansen
  • 11,584
  • 5
  • 52
  • 78

1 Answers1

2

With the caveat that there's no specification or standard for how the console behaves, the probable reason is that there's an important difference between the elements of a newly-constructed array and one that's had values (even undefined) explicitly assigned to array elements. The array essentially keeps track of whether a particular cell has ever been the target of an assignment (which the spread syntax effectively does). Those cells are treated differently in some important situations, mostly involving the various array iteration functions on Array.prototype. Those (well most of them) won't include never-assigned cells in the iteration.

So the console is showing you that your array allocated with the Array constructor and a numeric argument has a length of 6, but it's "empty" in the JavaScript array sense because none of the cells has been the target of any sort of assignment.

Again, don't rely on the particular output style of the console. Firefox and IE may show different things, and any browser might change the look of such output from release to release on a whim.

Pointy
  • 405,095
  • 59
  • 585
  • 614