Skipped holes in JavaScript Arrays

1 min read

This post is part of my Today I learned series in which I share all my learnings regarding web development.

Today I came along a code example that used the delete operator to remove an element from an array. This is an operation that is rarely useful IMO because it creates holes in an array.

let foo = [ 1, 2, 3, 4 ];

delete foo[ 1 ];
delete foo[ 2 ];

console.log( foo );
// logs in Chrome '[1, 3: 4]'

console.log( foo.length );
// logs in Chrome '4'

console.log( foo.toString() );
// logs in Chrome '1,,,4'

I think everybody should avoid holes in arrays, but I kept reading about it out of curiosity and discovered that array methods like forEach skip holes in arrays. I didn't know that. This makes sense, but bugs caused by this can takes ages to be found.

let foo = [ 1, 2, 3, 4 ];
delete foo[ 1 ];

foo.forEach( ( value, index ) => console.log( index, value ) );
// 0 1
// 2 3
// 3 4

At the end I'll still avoid the usage of the delete operator for arrays to not create holes, but I think it's good to know about these things...

If you want to read more about this topic I highly recommend you to check out Axel Rauschmayers's section about holes in JavaScript arrays in "Speaking JavaScript".

Load time