Array.slice() and Array.splice()

Sagar Kumar JhaSagar Kumar Jha
2 min read

Array.slice():

The array.slice() method returns the selected elements starting at the given start argument and ends at the given optional end argument without including the last element. If you omit the second argument then it selects till the end.

Example:

let arrayIntegers = [1,2,3,4,5];
let arrayIntegers1 = arrayIntegers.slice(0,2); // returns [1, 2]
let arrayIntegers2 = arrayIntegers.slice(1,2); // returns [3]
let arrayIntegers3 = arrayIntegers.slice(4); // returns [5]

Note: Slice method won't mutate the original array but it returns the subset as a new array.

Array.splice()

The array.splice() method is used either adds/removes items to/from an array, and then returns the removed item. The first argument specifies the array position for insertion or deletion whereas the option second argument indicates the number of elements to be deleted. Each additional argument is added to the array.

Some of the examples of this method are,

let arrayIntegersOriginal1 = [1, 2, 3, 4, 5];
let arrayIntegersOriginal2 = [1, 2, 3, 4, 5];
let arrayIntegersOriginal3 = [1, 2, 3, 4, 5];

let arrayIntegers1 = arrayIntegersOriginal1.splice(0,2); // returns [1, 2]; original array
let arrayIntegers2 = arrayIntegersOriginal2.splice(3); // returns [4, 5]; original array:
let arrayIntegers3 = arrayIntegersOriginal3.splice(3, 1, "a", "b", "c"); //returns [4];

Note: Splice method modifies the original array and returns the deleted array.

Difference between slice() and splice() in JavaScript

Featureslice()splice()
PurposeReturns a shallow copy of a portion of an arrayChanges the contents of an array by removing, replacing, or adding elements
Mutates original?❌ No – it returns a new array✅ Yes – it modifies the original array
Return valueNew array with selected elementsArray of removed elements (if any)
Argumentsslice(start, end)splice(start, deleteCount, ...items)
Use casesTo copy part of an arrayTo remove, replace, or insert elements
0
Subscribe to my newsletter

Read articles from Sagar Kumar Jha directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sagar Kumar Jha
Sagar Kumar Jha

Softwares are art and I am an artist