PASSWORD RESET

Your destination for complete Tech news

What is the difference between delete and splice in Javascript?

244 0
< 1 min read

In JavaScript, delete is an operator that is used to delete a property from an object. It does not modify the original object, but rather creates a new object with the property removed. delete only works on object properties and does not work on array elements.

Here is an example of how to use the delete operator:

let obj = {name: "John", age: 30};
delete obj.age;
console.log(obj);  // {name: "John"}

In contrast, splice() is a method that is used to modify an array by removing, adding, or replacing elements. It modifies the original array and returns an array containing the removed elements.

Here is an example of how to use the splice() method:

let arr = [1, 2, 3, 4, 5];
let removed = arr.splice(1, 2);  // removes elements at index 1 and 2 (2 and 3)
console.log(arr);  // [1, 4, 5]
console.log(removed);  // [2, 3]

In this example, the splice() method removes the elements at index 1 and 2 (2 and 3) from the array and returns them in a new array. The original array is modified to contain only the elements at index 0 and 3 (1 and 4).

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.