by Sai gowtham

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 a copy of the particular portion of the array into a new array.it doesn’t modify the original array as splice does.

suppose we need a copy of the first two fruits from the original fruits 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'];

If we need a copy of the middle fruits.

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…

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course