How to delete an element in an array using splice and delete and what is the difference between them both?.
3 min read
But do you really know what is the difference between the both?. Well, you have come to the right place. Keep reading!!!
As part of this blog, we are going to see
- What is delete operator?
- What is splice?
- What is the difference between splice and delete?
- What is the best way to delete an element?.
Define delete operator
According to MDN docs,
Syntax : delete expression
where expression should evaluate to
delete object.property delete object['property']
Lets see an example
let items_delete = [1,2,3,4,5]; items_delete.length; //Returns 5 delete items_delete; items_delete.length; //Returns 5 console.log(items_delete); // Returns [1,2,empty,4,5]
In the above example,
- lets declare and initialize an array with 5 items, whose length is returned as 5.
- In the next step using delete operator delete the third item in the array.
- When you check the length of the array after deletion it will still return as 5.
- As a final step when you try to print the array again you will see that in the position of third key, the value will be seen as empty.
Define splice operator
According to MDN docs
The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
let items_splice = [1,2,3,4,5]; items_splice.length; //Returns 5 items_splice.splice(3,1); items_splice.length; //Returns 4 console.log(items_delete); // Returns [1,2,4,5]
In the above example,
- let's declare and initialize an array with 5 items, whose length is returned as 5.
- In the next step using splice method delete the third item in the array.
- When you check the length of the array after deletion it will still return as 4.
- As a final step when you try to print the array again you will see that only 4 items are present in the array.
Difference between delete and splice
So by the example what we see is
- Delete - will delete the element and replace it with empty/defined, which means the length of the array always remains the same.
- Whereas when you use splice to delete an element, it removes the value or the index associated with it, which means the length of the array also changes.
What is the preferred method?.
Based on the example we have seen above, when you want to delete an element in the array it is best to use splice, since delete will result in an empty placeholder.
Now you should know the difference between splice and delete and which one to use during development.
Are you more of a Twitter person?. Then you can read the same thing in the below thread
Follow me on Twitter | LinkedIn for more web development related tips and posts. Feedbacks and suggestions are welcome.
Checkout my other blog post series
Did you find this article valuable?
Support Kritika Pattalam Bharathkumar by becoming a sponsor. Any amount is appreciated!