Hello Sunil
JavaScript slice and splice array methods

The Battle – Slice() vs Splice()

When it comes to working with JavaScript arrays, one of the most common mistakes is confusing slice with splice. They are both built-in array methods, both return a subarray from a specified range, and their names are awfully similar.

However, there are some key distinctions in their behavior.

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.

Also Read: JavaScript Slice Method – Practical Examples

Syntax:

arr.slice(start, end)

Here, arr is an array.

  • start (optional) – Starting index of the selection. If not provided, the selection starts at start 0.
  • end (optional) – Ending index of the selection (exclusive). If not provided, the selection ends at the index of the last element.

Let’s slice an array with no arguments:

let favoriteFood = ["🍕", "🍔", "🌮", "🍨"];
let slicedArray = favoriteFood.slice();

console.log(slicedArray); // ["🍕", "🍔", "🌮", "🍨"]

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

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

let favoriteFood = ["🍕", "🍔", "🌮", "🍨"];
let slicedArray = favoriteFood.slice(1);

console.log(slicedArray); // ["🍔", "🌮", "🍨"]

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.

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.

let favoriteFood = ["🍕", "🍔", "🌮", "🍨"];
let slicedArray = favoriteFood.slice(1, 3);

console.log(slicedArray); // ["🍔", "🌮"]

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); // ["🍔", "🌮", "🍨"]

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.

So, 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.

Splice() Method

The splice() method helps you add, update, and remove elements in an array.

splice() is destructive. This means it alters the original 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.

Also Read: JavaScript Splice – Delete, Insert, and Replace

Syntax:

arr.splice(start, deleteCount, item1, ..., itemN)

Here, arr is an array.

  • start – The index from where the array is changed.
  • deleteCount (optional) – The number of items to remove from start.
  • item1, …, itemN (optional) – The elements to add to the start index. If not specified, splice() will only remove elements from 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.

let favoriteFruits = ["🍓", "🥑", "🍊", "🍇"];
let removedFruits = favoriteFruits.splice(2);

console.log(favoriteFruits); //  ["🍓", "🥑"]
console.log(removedFruits); //   ["🍊", "🍇"]

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); //   ["🥑", "🍊", "🍇"]

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); //   ["🥑", "🍊"]

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.

let favoriteFruits = ["🍓", "🥑", "🍊", "🍇"];
let removedFruits = favoriteFruits.splice(1, 1, "🍏", "🍒");

console.log(favoriteFruits); //  ["🍓", "🍏", "🍒", "🍊", "🍇"]
console.log(removedFruits);  //   ["🥑"]

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()Splice()
Does not modify the original arrayModifies the original array
Returns selected elements
from the array
Returns removed elements
from the array
Can’t add new elements Can add new elements to array

Conclusion

We hope this post helps you clear the confusion between these two methods. You use one trick to remember things: the letter “p” of the splice() referred to as permanently modifying the array. We hope it will help you as well 😊.

Happy Coding!

Resource

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there 👋 I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.