My Development Notes


JavaScript Array splice() vs slice() methods


The splice() method is used to add or remove multiple elements in an array. It can add in or remove any number of consecutive elements from anywhere inside the array. It also overwrites the original array. It can take up to three parameters, the third one basically comprising of elements to add to an array.

Here’s an example of splice() method with two parameters :

let arr = [ 2,3,4,5,6,7];
arr.splice(2,4);
console.log(arr)

// outputs [2,3] (i.e., at index 2 remove four items)

Here’s another example of splice() :

let arr = [ 2,3,4,5,6,7];
arr.splice(2,2);
console.log(arr);

// outputs [2,3,6,7] (i.e., at index-2 remove two items)

Here’s an example of splice() with three parameters comprising of one or more elements in the end to add to an array :

let arr = ['cat','rat','dog'];
arr.splice(2,2,'horse','tiger');
console.log(arr);

// outputs ['cat','rat','horse','tiger'] (i.e., at index-2 remove the original item and add horse and tiger)

Here’s another example to make everything clear:

let arr = ['cat','rat','dog'];
arr.splice(2,0,'horse','tiger');
console.log(arr);

// outputs ['cat','rat','horse','tiger','dog']

The slice() method on the other hand copies a given number of elements of an array into another array, leaving the original array untouched.

It takes two parameters – the first parameter is the index at which copying starts and second is the parameter at which the copying stops, the second parameter not included.

The below code example will make it clear:

let arr = ['cat', 'rat', 'horse', 'tiger', 'dog'];
let animals = arr.slice(2,4);
console.log(animals);

//outputs ['horse','tiger']

Leave a Reply

Your email address will not be published. Required fields are marked *