Sparse Arrays and Empty Slots
You'll learn: What happens when you skip indices while creating or modifying arrays, leaving "holes" in your data structure.
What Are Sparse Arrays?
In JavaScript, arrays don't have to be packed densely with values. When you skip indices—either by setting a value at a large index or by skipping positions in an array literal—you create a sparse array with empty slots (also called "holes").
These aren't the same as undefined values. Empty slots are truly absent entries that JavaScript tracks differently.
Creating Sparse Arrays
You can create sparse arrays in several ways:
// Skipping commas in array literals
let sparse1 = [1, , , 4]; // Two empty slots at indices 1 and 2
// Setting an element beyond current length
let sparse2 = [10, 20];
sparse2[5] = 60; // Creates empty slots at indices 2, 3, and 4
// Using the Array constructor with a number
let sparse3 = new Array(3); // Three empty slots
How Empty Slots Behave
Empty slots affect the length property but don't contain any value:
let arr = [1, , 3];
console.log(arr.length); // 3
console.log(arr[1]); // undefined (but it's an empty slot!)
console.log(1 in arr); // false (proves the slot is truly empty)
console.log(0 in arr); // true (index 0 has a value)
Think of it like a hotel: A sparse array is a hotel where rooms 1 and 3 are occupied, but room 2 doesn't even exist yet—it's not just an empty room, it's not built!
Key Takeaway: Sparse arrays have gaps where indices are skipped, creating empty slots that JavaScript treats differently from explicit undefined values. The length property counts these holes, but the slots contain nothing.