Array slice v/s splice once and for all!

Array slice v/s splice once and for all!


📅  28 Jun 2020 | ☕️  2 Min Read

Hey There! 👋🏽

If you are like me and have spent most of your recent years coding in Javascript you definitely have come across this conundrum: There is this array and you want to do an operation on it to get a transformed version. You know there exists a slice as well as a splice method on the Array prototype but still, open google, type javascript array slice, then javascript array splice, compare them and then make your decision, every single time!

Do you wish to break this loop and become a JS array ninja who just knows which one of the two is to be used in which case? Then follow along.


To the uninitiated, Javascript provides us with two methods on the Array prototype which look ever so similar but function worlds apart. There is


Returns a section of the original string without changing the original string

let str = [1,2,3,4,5,6,7];
console.log(str.slice(4)); // [5, 6, 7]
console.log(str) // [1,2,3,4,5,6,7];


Changes the contents of the array by removing/replacing existing items

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

Here is a mnemonic technique that you can use so that there is no need for another Google search in your entire life while working on JS arrays.

Slice v/s Splice

Notice that splice has an extra p in the method name. Because of that, it pulls the items out of the original array and hence modifies it, and thus, slice does not pull items out of the original array. Also, because it pulls items, it can also push items into the array.

So let's sort this out:

slice(startIndex, endIndex)

It takes a start index and an end index (excluded) and slices those array items and gives back to you.

let str = [1,2,3,4,5,6,7];
console.log(str.slice(2, 4)); // [3, 4]
console.log(str) // [1,2,3,4,5,6,7]; // not modified

splice(startIndex, number, items)

It takes a start index too, but, also pulls the items out of the original array (the number of items can be specified in the number argument) and all the other arguments after than will be pushed into the array!

let str = [1,2,3,4,5,6,7];
console.log(str.splice(2,4,8,9)); // [3, 4, 5, 6]
console.log(str) // [1, 2, 8, 9, 7];

Here's a graphic to cement that understanding


Original : Array slice v/s splice once and for all!

© 2020 built with 🔥 by Iyan Saputra