Slice vs Splice in JS
Ustariz Enzo
Posted on December 8, 2021
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)
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)
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)
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.
Posted on December 8, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024