- Published at
- Updated at
- Reading time
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...