Slice vs Splice: Understanding the Difference Between Two Essential JavaScript Array Methods

·

2 min read

In this article, You will understand when and how to use Slice and Splice methods in JavaScript.

Both methods are often used to extract, remove or replace and add items to an array.

Slice method:

Syntex: arr.slice(start_index, end_index)

The Slice method extracts a subarray without modifying the original array. This method takes two parameters: start_index (optional) and end_index (optional) of the subarray that we want to get.

const arr = ['a', 'b', 'c', 'd'];

// if you don't specify any parameters, you get a copy of the arr
const copyArr = arr.slice(); // ['a', 'b', 'c', 'd']

// if you specify one parameter, then slice will copy from that parameter to last index 
const subArr1 = arr.slice(2); // returns ['c', 'd']

// If you specify both parameters: first and end,then slice will copy elements from first index to end-1 index. 

const subArr2 = arr.slice(1, 3); // returns ['b', 'c']

Splice method:

The Splice method is used to remove, replace and add items to an array.

Splice returns an array of deleted items.

And Splice modifies the original array, unlike Slice.

Syntex: arr.splice(start, delete_count, item1, item2, itemN)

const arr = ['a', 'b', 'c', 'd', 'e'];

// remove 2 items from index 1
let removed_items = arr.splice(1, 2);
console.log(removed_items); // ['b', 'c']
console.log(arr); // ['a','d', 'e']

// replace item at index 1 with 2 items - 'p' and 'r'.
let removed_items = arr.splice(1, 2, 'p', 'r');
console.log(removed_items);// ['d', 'd']
console.log(arr); // ['a', 'p', 'r', 'e']

// adding 'z' at 0 index. Here deleteCount(second parameter) is 0, so no item will be deleted. 

let removed_items = arr.splice(0, 0, 'z');
console.log(removed_items);// []
console.log(arr); // ['z', 'a', 'p', 'r', 'e']

Comparison

In the below table, you can see what are the key differences between Splice and Slice.

Summary

In summary, both methods are pretty useful to manipulate an array.

You should use the Slice method when you want to extract a portion of an array without modifying the original array.

And use the Splice when you want to modify the original array by adding or removing items.