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.