I have to admit that the amount of Javascript code I write is really limited. And even then I use TypeScript most of the time. Anyway this is only a disclaimer because maybe I'm stating something that is obvious to you. It certainly wasn't to me :-)!
I had a really simple use case to solve: I needed to delete a specific item from an array .I didn’t know the exact function name anymore so I asked Google and got back with the delete operator.
This turns out to the wrong approach as the delete operation will delete a property from an object and set it to undefined:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var arrayItems = ['a' , 'b' , 'c' ]; | |
arrayItems.length; // returns 3 | |
delete arrayItems[1]; // returns true | |
arrayItems.length; // returns 3 | |
console.log(arrayItems); // [ 'a', undefined, 'c' ] |
The correct way is to use the splice function:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var arrayItems = ['a' , 'b', 'c' ]; | |
arrayItems.length; // returns 3 | |
//Delete one item starting from position 1 | |
arrayItems.splice(1,1); // returns true | |
arrayItems.length; // returns 2 | |
console.log(arrayItems); // [ 'a', 'c' ] |
I hope I never forget it anymore!