Slice and Splice
let arrayDefinition = ; // Array declaration in JS
Now let’s declare another array with different data types. I will use it below in examples:
let array = [1, 2, 3, "hello world", 4.12, true];
Slice ( )
The slice( ) method copies a given part of an array and returns that copied part as a new array. It doesn’t change the original array.
- From: Slice the array starting from an element index
- Until: Slice the array until another element index
For example, I want to slice the first three elements from the array above. Since the first element of an array is always indexed at 0, I start slicing “from”0.
Now here is the tricky part. When I want to slice the first three elements, I must give the until parameter as 3. The slice( ) method doesn’t include the last given element.
array --> 1 // included
array --> 2 // included
array --> 3 // included
array --> "hello world" // not included
This can create some confusion. That’s why I call the second parameter “until”.
let newArray = array.slice(0, 3); // Return value is also an array
Finally, I assign the sliced Array to the newArray variable. Now let’s see the result:
Important Note: the Slice( ) method can also be used for strings.
Splice ( )
The name of this function is very similar to slice( ). This naming similarity often confuses developers. The splice( ) method changes an array, by adding or removing elements from it. Let’s see how to add and remove elements with splice( ):