Skipped holes in JavaScript Arrays
- Published at
- Updated at
- Reading time
- 2min
Today I came across a code example that used the delete
operator to remove an array element. This operation is rarely helpful because it creates array holes.
Arrays with holes are called sparse arrays.
let numbers = [1, 2, 3, 4];
delete numbers[1];
delete numbers[2];
console.log(numbers);
// Chrome log: (4) [1, empty × 2, 4]
// Firefox log: Array(4) [ 1, <2 empty slots>, 4 ]
console.log(numbers.length);
// Chrome log: 4
// Firefox log: 4
console.log(numbers.toString());
// Chrome log: '1,,,4'
// Firefox log: '1,,,4'
I read more about sparse arrays and discovered that array methods like forEach
skip the array holes. I didn't know that!
Bugs caused by array holes can take ages to be found, which is why I'll avoid sparse arrays.
let numbers = [ 1, 2, 3, 4 ];
delete numbers[ 1 ];
numbers.forEach((value, index) => console.log(value, index));
// 1, 0
// 3, 2
// 4, 3
delete
is not the only way to create sparse arrays. There's more!
Sparse arrays with an array literal
The following results in a whole at index 1
with the length of 3
.
const numbers = [1, , 2];
// Array(3) [ 1, <1 empty slot>, 2 ]
Sparse arrays with the Array constructor
The following results in an empy array with the length of 3
.
const numbers = Array(3);
// Array(3) [ <3 empty slots> ]
Sparse arrays with the redefinition of length
The following results in an array with values at 0
, 1
and 2
with the length of 10
.
const numbers = [1, 2, 3];
numbers.length = 10;
// Array(10) [ 1, 2, 3, <7 empty slots> ]
I avoid sparse arrays, but I think it's good to know this JavaScript quirk.
If you want to read more about holes in JavaScript arrays, check Axel Rauschmayers's section about holes in JavaScript arrays in "Speaking JavaScript".
Join 5.5k readers and learn something new every week with Web Weekly.