Empty Slots Are Bad In Javascript Arrays

Question 1

Answer me, what’s the value of

[0, , 2][1]

The correct answer is

undefined

Question 2

Again, what’s the output of

let array = [0, , 2]
while (array.length) {
  console.log(array.shift())
}

Yes, it’s simple, the answer is

0
undefined
2

Question 3

One more time, what’s the output of

[0, , 2].forEach(
  e => console.log(e)
)

You think it’s the same as question 2? No, dude~ It’s

0
2

That’s absolutely ridiculous! Right? If you don’t believe it, test for yourself.

Why? Why? Why?

Every time you put two commas in a row, the array leaves an empty slot. It’s “empty”, not the same as undefined.

Accessing an empty slot with index or index methods like .shift() returns undefined. But traversing methods like .forEach() skips empty slots.

This is bad, breaks consistency of the language.

How Empty Slots Exist

Extra Commas In the Middle

console.log(
  [0, , 2]
)
// outputs [0, empty, 2]

The extra comma in the middle leads to an empty slot.

Extra Commas At the Beginning

console.log(
  [, 1, 2]
)
// outputs [empty, 1, 2]

The extra comma at the beginning also leads to an empty slot.

Extra Commas At the End

console.log(
  [0, 1, ,]
)
// outputs [0, 1, empty]

You might think the output should be

// [0, 1, empty × 2]

Actually, no. Because an empty slot exists only before an extra comma, the extra commas at the end leads to only one empty slot.

Define an Array with new Array()

console.log(
  new Array(4)
)
// outputs [empty × 4]

If you define a specific-length array with new Array(<length>), each item in the array is an empty slot. This kind of array is called an “holey” array.

How to Avoid Empty Slots

When defining an array with [], make sure don’t put any extra commas, except at the very end. You may use undefined to stand for an undetermined item.

let bad = [, 0, , 2, ,]
let good = [undefined, 0, undefined, 2, undefined,]

If new Array()1 is your thing, there are two best ways to avoid empty slots.

Use spread operator2

console.log(
  [...new Array(5)]
)
// outputs [undefined, undefined, undefined, undefined, undefined] 

Or Array.prototype.fill()3

console.log(
  new Array(5).fill(undefined)
)
// outputs [undefined, undefined, undefined, undefined, undefined] 

Array.prototype.fill() is more flexible if you need initial values other than undefined.

console.log(
  new Array(5).fill("")
)
// outputs ['', '', '', '', '']

Summary

Empty slots in arrays break javascript language consistency.

To avoid empty slots, don’t use extra commas, except it’s the very end of an array.

When defining an array with new Array(<length>), make sure to use the spread operator ... or .fill().

Footnotes

  1. Array() constructor.

  2. Spread syntax.

  3. Array.prototype.fill().