DEV Community

Cover image for Slice and Splice JavaScript Arrays Like a Pro
Sumudu Siriwardana
Sumudu Siriwardana

Posted on

Slice and Splice JavaScript Arrays Like a Pro

This article was originally published on Dasha.

In case you are wondering, Dasha is a conversational-AI-as-a-service platform that lets you embed realistic voice and text conversational capabilities into your apps or products. Start building for free!


Do you find yourself looking up the difference between slice() and splice() methods all the time?

The two methods are among the most used array methods when it comes to adding, updating, or removing items in an array, and cloning an array or copying a portion of an array. โ€‹

Slice() and splice() methods look similar, and they sound similar, so it's very easy to get confused and remember which is which. I've put together this guide on these two methods so that you can slice and splice JavaScrips arrays like a pro.

slice-vs-splice.png

Slice() Method

The slice() method copies a chunk (or slice) from an array and returns that copied part as a new array. It does not modify or change the original array. Instead, it creates a new shallow copy of the original array.

This method takes two optional arguments. The first argument is the startIndex, and the second is the endIndex. If you do not pass any arguments, the entire original array will be copied by default. Also, If the arguments you pass are greater than the actual array, it will return an empty array.

Syntax

// No arguments
array.slice();

โ€‹// One argument
array.slice(startIndex);

โ€‹// Two arguments
array.slice(startIndex, endIndex);
Enter fullscreen mode Exit fullscreen mode

Parameters

  • startIndex:
    • The index where the slice should begin.
    • If the value is omitted, it will start at 0.
  • endIndex:
    • The slice will end before this index. So, for example, adding index 4 will slice up to index 3, omitting the value of index 4.
    • If the endIndex value is omitted, it will slice to the end of the array.

Let's slice an array with no arguments:

let favoriteFood = ["๐Ÿ•", "๐Ÿ”", "๐ŸŒฎ", "๐Ÿจ"];

let slicedArray = favoriteFood.slice();

console.log(slicedArray); // ["๐Ÿ•", "๐Ÿ”", "๐ŸŒฎ", "๐Ÿจ"]
console.log(favoriteFood === slicedArray);  //false
Enter fullscreen mode Exit fullscreen mode

In the above example, since there are no arguments, it has returned a copy of the entire array.

One important thing to note here is that these two arrays are not equal! They are two separate arrays containing the same values inside them. So if you check their equality as in the example, it will return false.

Now let's check how we can slice an array with a single argument.

let favoriteFood = ["๐Ÿ•", "๐Ÿ”", "๐ŸŒฎ", "๐Ÿจ"];

let slicedArray = favoriteFood.slice(1);

console.log(slicedArray); // ["๐Ÿ”", "๐ŸŒฎ", "๐Ÿจ"]
Enter fullscreen mode Exit fullscreen mode

When you pass a single argument to the slice() method, it grabs all the elements from that argument until the end of the array, including the index in the argument. So in our example, we have made a copy from index 1 to favoriteFood.length - 1.

Here's a visual representation of our example:

slice-example-1.gif

Let's move on to slicing an array by passing two arguments.

Imagine that we want to copy only the ๐Ÿ” and ๐ŸŒฎ from our previous example to a new array.

slice-example-2.gif

let favoriteFood = ["๐Ÿ•", "๐Ÿ”", "๐ŸŒฎ", "๐Ÿจ"];

let slicedArray = favoriteFood.slice(1, 3);

console.log(slicedArray); // ["๐Ÿ”", "๐ŸŒฎ"]
Enter fullscreen mode Exit fullscreen mode

โ€‹
In the above example,

  • We have added index 1 as the first argument. Remember that the first argument includes the index itself when slicing the array.
  • As the second argument, we have added index 3. But it doesn't include the index when slicing the array. Instead, it only includes the elements up to that index. In this case, it will grab only up to index 2. This array slice returns a new array with ๐Ÿ” and ๐ŸŒฎ.

Another thing that we can do with the slice() method is that use negative numbers for arguments. Let's see how this works with the below example.

let favoriteFood = ["๐Ÿ•", "๐Ÿ”", "๐ŸŒฎ", "๐Ÿจ"];

let slicedArray = favoriteFood.slice(-3);

console.log(slicedArray); // ["๐Ÿ”", "๐ŸŒฎ", "๐Ÿจ"]
Enter fullscreen mode Exit fullscreen mode

In the above example, we have added a single argument as -3. This will start counting from the end of the array and slice it (not the beginning from the array). If we have given -2, it will return only ["๐ŸŒฎ", "๐Ÿจ"]. This is very useful when you want to get the last element of the array, and then you just have to use -1.

The slice() method is very useful for cloning an array, copying a portion of an array, and converting an array-like object into an array.

slice-it-all.gif

Splice() Method

The splice() method helps you add, update, and remove elements in an array. This method modifies the array and does not create a new array. It will also return a new array with all the elements you have removed, which is helpful if you want to track what has been removed.

The splice() method takes several arguments to decide which elements to delete, the delete count, and what elements to add. You can check further details on these parameters below.

Syntax

// general
Array.splice(startIndex)

// With the optional parameters
Array.splice(start, deleteCount, newElement)
Enter fullscreen mode Exit fullscreen mode

Parameters

  • start(required):
    • The index where the slice should begin for removing elements in the array.
    • If the start is negative, it will count backward from the end of the array.
  • deleteCount (optional):
    • The number of elements to be deleted from that index.
    • If you don't specify the deleteCount, it will delete everything in the array after the startIndex.
  • newElement (optional): The new element(s) to be added to the array.

Let's see how to remove elements with a single argument, with only the start parameter.

We have our favorite fruits in the array below, and we want to remove the last two fruits.

splice-example-1.gif

let favoriteFruits = ["๐Ÿ“", "๐Ÿฅ‘", "๐ŸŠ", "๐Ÿ‡"];

let removedFruits = favoriteFruits.splice(2);

console.log(favoriteFruits); //  ["๐Ÿ“", "๐Ÿฅ‘"]
console.log(removedFruits); //   ["๐ŸŠ", "๐Ÿ‡"]
Enter fullscreen mode Exit fullscreen mode

In the above example, we have added the start parameter as 2, and that's where it has started removing things from this array. Since we haven't specified a second parameter, it has removed everything after index 2, including the index 2 element. So now the favoriteFruits only includes ["๐Ÿ“", "๐Ÿฅ‘"]. And you can see the removed item in the array, removedFruits.

If you add 0 as the start parameter without any other parameters, it will remove everything from the array and change it to an empty array. Also, if you add any number higher than the largest index number of the array, it will not affect the original array.

So what happens if we add a negative number as the start parameter? If the start is negative, it will count backward from the end of the array and remove the elements. Check the below example.

let favoriteFruits = ["๐Ÿ“", "๐Ÿฅ‘", "๐ŸŠ", "๐Ÿ‡"];

let removedFruits = favoriteFruits.splice(-3);

console.log(favoriteFruits); //  ["๐Ÿ“"]
console.log(removedFruits); //   ["๐Ÿฅ‘", "๐ŸŠ", "๐Ÿ‡"]
Enter fullscreen mode Exit fullscreen mode

In the above example, we have added the start parameter as -3. This will start counting from the end of the array and remove items. If we have given -2, the original array will return ["๐ŸŠ", "๐Ÿ‡"].

Now let's see how to remove elements with the start and deleteCount parameters.

Check the below example.

let favoriteFruits = ["๐Ÿ“", "๐Ÿฅ‘", "๐ŸŠ", "๐Ÿ‡"];

let removedFruits = favoriteFruits.splice(1, 2);

console.log(favoriteFruits); //  ["๐Ÿ“", "๐Ÿ‡"]
console.log(removedFruits); //   ["๐Ÿฅ‘", "๐ŸŠ"]
Enter fullscreen mode Exit fullscreen mode

In the above example, we removed elements starting from index 1 and removed two elements. And it has modified the original array with the remaining elements and returned an array with the removed elements.

So let's move on to adding elements to the array with the newElement parameter.

You can add a continuous list of elements separated by commas. Let's add two additional fruits to our favorite Fruits.

splice-exaple-3.gif

let favoriteFruits = ["๐Ÿ“", "๐Ÿฅ‘", "๐ŸŠ", "๐Ÿ‡"];

let removedFruits = favoriteFruits.splice(1, 1, "๐Ÿ", "๐Ÿ’");

console.log(favoriteFruits); //  ["๐Ÿ“", "๐Ÿ", "๐Ÿ’", "๐ŸŠ", "๐Ÿ‡"]
console.log(removedFruits);  //   ["๐Ÿฅ‘"]
Enter fullscreen mode Exit fullscreen mode

Let's see what we have done here:

  • We removed "๐Ÿฅ‘".
  • We set the deleteCount as 1 since we want to remove only one element.
  • And we added "๐Ÿ", "๐Ÿ’" to the array where we remove the elements.

We can add any number of elements to the array by separating them by commas. When we add elements to the array, the array will grow in length. Also, if you don't want to remove any items, you can simply add the second parameter as 0.
โ€‹
The splice() method is mainly used when you need to delete or add new elements to an array. And you can either assign the returned array to a variable or ignore it as you wish.

Now we have a clear idea about how slice() and splice() methods work. You can find out what's the main differences between these two methods below.

Slice() vs. Splice()

Slice() Splice()
Does not modify the original array Modifies the original array
This method is used to get a new array by selecting a sub-array of a given array. This method is used to add/remove an item from the given array.
The result has to be assigned to a new array variable. The result is not required to assign to a new variable.
Takes two arguments, both being optional. Takes 3 arguments, the last two arguments being optional, and the last argument can have any number of parameters (just remember that you don't have to pass it as an array type).
The second argument represents an index. The second argument represents the count.

Conclusion

I hope this post helps you clear the confusion between these two methods. I use one trick to remember things: the letter "p" of the splice() referred to as permanently modifying the array. I hope it will help you as well ๐Ÿ˜Š

Happy Coding!

happy-coding.gif


Visit Dasha AI
Join Dasha Developer Community where youโ€™ll meet welcoming like-minded developers who share ideas, questions, and get all the help they need to build cool conversational AI apps (for free, of course).

Top comments (2)

Collapse
 
bpsagar profile image
Sagar Chakravarthy

Before using slice or splice, one has to always Google to confirm what does what ๐Ÿ˜…

Nice one Sumudu ๐Ÿ™

Collapse
 
jdx_code profile image
Jyotirmoy Das

slice vs splice is really a head-scratching thing for beginners and even intermediates. This article really explained it well.