JavaScript Methods .splice() vs .slice() Explained!

JavaScript Methods .splice() vs .slice() Explained!

The splice and slice methods seem similar, but how are they really different? Well, read this blog for a better understanding!

If you want to know more about each method, please read my previous blogs on the splice method and the slice method.

The Difference between splice() and slice()

1. The splice() method modifies the original array, but the slice() method does not.

Have a look at this example. The original numbers array in the code below is [0, 1, 2, 3, 4]. The splice method changes the numbers array to [0, 1], but the slice method did not change the numbers array.

//splice method
const numbers = [0, 1, 2, 3, 4];
numbers.splice(2);
console.log(numbers);  // [0, 1] // the array changed!
//slice method
const numbers = [0, 1, 2, 3, 4];
numbers.slice(2);
console.log(numbers);  // [0, 1, 2, 3, 4] // the array didn't change

2. The splice method returns an array of the deleted items but the slice method returns a copy of the selected items.

The splice and slice methods both return an array of items. The difference is that the splice method returns the items removed from the original array to the new array, while the slice method returns a copy of the selected items to the new array without changing the original array.

//splice method
const numbers = [0, 1, 2, 3, 4];
const removedNumbers = numbers.splice(2, 2); //remove 2 items from index 2
console.log(removedNumbers);  // [2, 3]
//slice method
const numbers = [0, 1, 2, 3, 4];
const copiedNumbers = numbers.slice(2, 4); //select items from index 2 until index 4
console.log(copiedNumbers);  // [2, 3]

Reference

splice method (MDN Docs)

slice method (MDN Docs)