How to use splice and slice methods in JavaScript
In this tutorial, we are going to learn about how to use the splice()
and slice()
methods in JavaScript with the help of examples.
Splice method
The splice()
method helps us to remove the elements from the existing array and also insert
the new elements in the place of removed elements.
splice
method accepts three arguments.
start: In which index we need to start removing elements from the array.
deleteCount: how many elements we need to remove from the array.
item1, item2(optional): insert the new elements in the place of removed elements.(if you don’t specify new elements splice method will only remove elements).
Remove the 2 elements from index 0
const fruits= ['oranges','grapes','mangoes','bananas'];
fruits.splice(0,2);
console.log(fruits); // ['mangoes','bananas']
Remove the 2 elements from index 0 ,and insert 2 new elements.
const fruits= ['oranges','grapes','mangoes','bananas'];
fruits.splice(0,2,'apples','Avocados');
console.log(fruits); // ['apples','avocados','mangoes','bananas']
Remove 3 elements from index 2.
const vegetables = ['broccoli','corn','cucumber','lettuce', 'pumpkin','tomato'];
vegetables.splice(2,3);
console.log(vegetables); // ['broccoli','corn','tomato'];
Slice method
The slice()
method helps us to get the copy of an array, it doesn’t modify the original array as splice does.
In this example, we are getting the copy of first two elements from the following array.
const fruits = ['apples','avocados','mangoes','bananas'];
console.log(fruits.slice(2)); // ['apples','avocados']
// original array stays same.
console.log(fruits); //['apples','avocados','mangoes','bananas'];
another example:
const fruits = ['apples','avocados','mangoes','bananas'];
console.log(fruits.slice(1,2)); // ['avocados','mangoes']
Difference between the splice and slice methods
- splice method modifies the original array and also insert the new elements in the place
of removed elements.
- slice method returns a copy from the original array but it can’t insert or modify
the original array.
Happy coding…