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…


This content originally appeared on DEV Community and was authored by Ustariz Enzo

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/Learntocreate/videos

See you soon!

Enzo.


This content originally appeared on DEV Community and was authored by Ustariz Enzo


Print Share Comment Cite Upload Translate Updates
APA

Ustariz Enzo | Sciencx (2021-12-08T12:20:39+00:00) Slice vs Splice in JS. Retrieved from https://www.scien.cx/2021/12/08/slice-vs-splice-in-js/

MLA
" » Slice vs Splice in JS." Ustariz Enzo | Sciencx - Wednesday December 8, 2021, https://www.scien.cx/2021/12/08/slice-vs-splice-in-js/
HARVARD
Ustariz Enzo | Sciencx Wednesday December 8, 2021 » Slice vs Splice in JS., viewed ,<https://www.scien.cx/2021/12/08/slice-vs-splice-in-js/>
VANCOUVER
Ustariz Enzo | Sciencx - » Slice vs Splice in JS. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/12/08/slice-vs-splice-in-js/
CHICAGO
" » Slice vs Splice in JS." Ustariz Enzo | Sciencx - Accessed . https://www.scien.cx/2021/12/08/slice-vs-splice-in-js/
IEEE
" » Slice vs Splice in JS." Ustariz Enzo | Sciencx [Online]. Available: https://www.scien.cx/2021/12/08/slice-vs-splice-in-js/. [Accessed: ]
rf:citation
» Slice vs Splice in JS | Ustariz Enzo | Sciencx | https://www.scien.cx/2021/12/08/slice-vs-splice-in-js/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.