Day #2 Pro Tip #Javascript
Don’t use delete to remove an item from array
Published in
1 min readMar 24, 2018
Use splice
instead of using delete
to delete an item from an array. Using delete
replaces the item with undefined
or empty
instead of the removing it from the array.
Instead of…
var items = ['manjula','vihang' ,'arwa','sahil', 'foo' , , 'Doe'];
items.length; // returns 7
delete items[3]; // return true
items.length; // returns 7
/* items will be equal to ["manjula", "vihang", "arwa", empty, "foo", empty, "Doe"] */
Use the below…
var items = ['manjula','vihang' ,'arwa','sahil', 'foo' , , 'Doe'];
items.length; // returns 7
items.splice(3,1) ;
items.length; // returns 6
/* items will be equal to ["manjula", "vihang", "arwa", "foo", empty, "Doe"] */
The delete method should be used to delete an object property.
Thanks for reading !!
Stay tuned for more tips