Slice and Splice

JavaScript Arrays

Firstly, you need to understand how JavaScript arrays work. Like in other programming languages, we use arrays to store multiple data in JS. But the difference is that JS arrays can contain different type of data at once.

Sometimes we need to do operations on those arrays. Then we use some JS methods like slice () & splice (). You can see below how to declare an array in JavaScript:

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];

This usage is valid in JavaScript. An array with different data types: string, numbers, and a boolean.

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.

array.slice(from, until);

  • 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.

array.slice(0, until);

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[0] --> 1              // included
array[1] --> 2 // included
array[2] --> 3 // included
array[3] --> "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( ):

I am a product-focused web developer. My expertise is in web technologies, particularly JavaScript,Ruby,Python,React and Redux.