Slice vs Splice

Kat Leight
2 min readApr 27, 2021

I’ve been doing a lot of algorithms practice lately and I know that both slice and splice are vaguely floating out in the JavaScript universe. . . but I can never remember how to use them. So, I decided to put them both in terms I can understand and remember: baking.

SLICE

Slice returns a new array of selected elements that you’ve sliced out of an old array.

Think of a cake. You want to eat a piece of that cake. In order to do so, you must SLICE yourself out a piece.

Unlike real cake, the original cake (array) will remain the same (non-destructive). So, you can slice neatly!

You can give it a start and end argument (of indices in the array, both optional), but note, the slice will not include the end argument.

array.slice(start, end)

If you pass in NO start or end, it simply clones the original array.

OR if you want just the LAST item (in my case of cake, just the frosting), you can pass in -1 as a starting point to give you the last item in the array.

array.slice(-1,1)

SPLICE

Unlike the lovely SLICE method, SPLICE is DESTRUCTIVE! It will change the contents of the original array by removing or replacing items.

If SLICE is used for cakes, I think of SPLICE being like modifying the cake recipe. (Stick with me, I’m committed to this baking metaphor).

It also takes some arguments:

start (the index at which to start changing the array). If negative, it will being that many elements from the end of the array)

deleteCount (optional- the number of elements in the array to remove from start. if left out, all elements from start to the end will be deleted)

itemsToAdd (optional- elements to add to the array, beginning from start)

splice(start)

splice(start, deleteCount)

splice(start, deleteCount, itemsToAdd)

And there you have it! Slice vs splice spelled out using my favorite love language: BAKED GOODS!

--

--

Kat Leight

Full Stack Developer. Prior Project Manager. Lover of cinnamon rolls and the great outdoors.