This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
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".
Reply to Stefan
This content originally appeared on Stefan Judis Web Development and was authored by Stefan Judis
![](https://www.radiofree.org/wp-content/plugins/print-app/icon.jpg)
Stefan Judis | Sciencx (2017-03-03T13:00:00+00:00) Skipped holes in JavaScript Arrays (#tilPost). Retrieved from https://www.scien.cx/2017/03/03/skipped-holes-in-javascript-arrays-tilpost/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.