Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

What happens when you assign past the end of a JavaScript array?

Do you know what will be the output of this code?

JavaScript
let array = [1, 2, 3];
array[6] = 9;
console.log(array[5]);
Show answer and explanation

The answer is undefined.

This quiz starts with an array of length 3, containing 3 numbers.

By not using Array.prototype.push and then assigning a value to a position in the array that is out of the bounds of the original array, the array is extended automatically by the runtime while also increasing the length property.

But this leads to the interesting behavior that a lot of holes are created within the array.

After the expression array[6] = 9; the array looks as follows:

//  0  1  2     3           4          5      6     <- indices
   [1, 2, 3, undefined, undefined, undefined, 9]

And this is why, when accessing array[5], undefined is returned.

Take the full quiz Next question →

More Arrays questions

  1. Why does [33, 2, 8].sort() not sort numbers correctly?
  2. Why does [1, 2, 3].map(parseInt) return [1, NaN, NaN]?
  3. What does Array.push() return in JavaScript?
  4. How do you remove duplicates from an array with Set?
  5. What does Array.from({ length: 3 }) create?

Related topics