Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

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> ]

Conclusion

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".

If you enjoyed this article...

Join 5.2k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles