DEV Community

Cover image for Slice vs Splice in JS
Ustariz Enzo
Ustariz Enzo

Posted on • Edited on

Slice vs Splice in JS

Hey fellow creators

You've never quite known what the difference was between Slice and Splice in Javascript? Dive in!

If you prefer to watch the video version, it's right here :

1. Slice.

Slice will return a new array from an existing one. For example:

const array = ["kiwi", "strawberry", "lemon", "peach", "grape"];
const slicedArray = array.slice(0,2)

console.log(slicedArray)
Enter fullscreen mode Exit fullscreen mode

Here, slicedArray will return the existing array from index 0 to index 1 without including it, meaning the first two elements of array, kiwi and strawberry.

2. Splice.

Splice, however, will not return a new array but will simply remove or replace a portion of the existing array.

const array2 = ["kiwi", "strawberry", "lemon", "peach", "grape"];
array2.slice(0,1)

console.log(array2)
Enter fullscreen mode Exit fullscreen mode

It will remove an element from the beginning of the index, meaning the first fruit will be removed from the array.

You can also replace an element with another one:

const array2 = ["kiwi", "strawberry", "lemon", "peach", "grape"];
array2.slice(0,1, "lime")

console.log(array2)
Enter fullscreen mode Exit fullscreen mode

Here, "kiwi" will be replaced by "lime", but there will still be 5 elements to the array.

Know the difference now? As you can see, it's not that hard ;)

Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool

See you soon!

Enzo.

Top comments (0)