Array.splice and Array.slice in JavaScript

August 09, 2019

You must have used the above functions available in the JavaScript Array’s prototype. They look so similar, at times even I get confused between the two.



Key Difference

Array.splice

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
arr.splice(fromIndex, itemsToDelete, item1ToAdd, item2ToAdd, ...);

Removing the elements

var deletedItems = arr.splice(3, 2);
deletedItems // [3, 4]
arr // [0, 1, 2, 5, 6, 7, 8]

Adding new elements

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
var arr2 = arr.splice(2, 0, 100, 101);
arr2 // [] , since we didn't deleted an element from an array
arr // [0, 1, 100, 101, 2, 3, 4, 5, 6, 7, 8]

Modifying an existing element

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
var arr2 = arr.splice(3, 1, 100);
// which means - at index 3, delete 1 element and insert 100
arr2 // [3] as we deleted the element 3 from the arrayarr // [0, 1, 2, 100, 4, 5, 6, 7, 8]
// 3 gets replaced with 100 in array arr

Array.slice

Array.slice signature

arr.slice(startIndex, endIndex);
const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8];
var slicedArr = arr.slice(2, 6);
arr // [0, 1, 2, 3, 4, 5, 6, 7, 8]
slicedArr // [2, 3, 4, 5]

You Might Also Like

0 comments

Follow by Email