Catalin Vasile

I'm a design-focused engineer.

JavaScript Bits: slice() vs splice()

A common confusion among developers is the difference between how the slice() and splice() Array methods work.

A really short summary would be that slice() is a non-mutative method that provides a way of removing items from an Array. The splice() method on the other hand is a mutative method that can be used for removing, adding and updating items from an Array.

Without wasting any more time, let’s dive deep and explore in no more than 5 minutes how both methods work. 😅

slice(start, [end])

The slice(start, [end]) method returns a portion of an Array from the start, but not including the end. If the end is ommited, the Array’s length property would be used instead (basically its end).

If a negative number is used with the slice() method, that will be counted from the end.

Finally, slice() returns a completely new Array that contains the removed values from the initial Array. It’s important to note that the original Array is not mutated (changed) at all and it remains intact.

Let’s see exactly how it looks! However, before we start, I think it’s best to think of the verb “remove” more like “extract”. I think it makes more sense that way.

// Create an Array with 4 items.
const myArray = ['zero', 'one', 'two', 'three'];

// Remove the first two items (remove only the items indexed 0 and 1)
const removed = myArray.slice(0, 2);

console.log(myArray);  // 'zero', 'one', 'two', 'three'
console.log(removed);  // 'zero', 'one'

That’s quite self explanatory. The only thing to be careful and remember is the fact that the end index (if defined) is not included as an item that has to be removed.

Also, not specifying the end index, would yield the following results.

// Create an Array with 4 items.
const myArray = ['zero', 'one', 'two', 'three'];

// Remove all the items starting at index 1.
const removed = myArray.slice(1);

console.log(myArray);  // 'zero', 'one', 'two', 'three'
console.log(removed);  //         'one', 'two', 'three'

Not specifying the second argument is the same as using the Array’s length as the second argument instead.

const myArray = ['zero', 'one', 'two', 'three'];

// Remove all the items starting at index 1.
const removed = myArray.slice(1, myArray.length);

console.log(myArray);  // 'zero', 'one', 'two', 'three'
console.log(removed);  //         'one', 'two', 'three'

See? They’re identical.

Now let’s try again, but using negative values for the second argument and see how that works.

const myArray = ['zero', 'one', 'two', 'three'];



// Remove all the items starting at index 1 until -1 (from the end).
const removed = myArray.slice(1, -1);

console.log(myArray);           // 'zero', 'one', 'two', 'three'
console.log(removed);           //         'one', 'two'



// Remove more  items starting at index 1 until -2 (from the end).
const moreItemsRemoved = myArray.slice(1, -2);

console.log(myArray);           // 'zero', 'one', 'two', 'three'
console.log(moreItemsRemoved);  //         'one'

Make sure you read the code carefully and let it sink so you can really understand how it works.

Once you’re done, let’s move on to splice().

splice(start, [deleteCount], […itemsToAdd])

The splice(start, [deleteCount], [...itemsToAdd]) method is more powerful compared to slice() as it allows you to not only remove items, but add or even update items.

Another major difference is that splice() is a mutative method (it changes the original Array).

Here’s how splice() works:

  • It accepts a first required parameter start which represents the start index.
  • The second optional parameter is deleteCount which represents how many items should be deleted from the start index.
  • The remaining (optional) parameters that are passed, represent the items that should be added beginning at the start index.
  • It changes the original Array and returns a new Array with the removed items.

That’s a lot to take in. Let’s see exactly how splice() works in code.

Removing items with splice()

const myArray = ['zero', 'one', 'two', 'three'];

// Remove all the items starting at index 1.
const removed = myArray.splice(1);

console.log(removed);  //        'one', 'two', 'three'
console.log(myArray);  // 'zero'

As you can see, removing the items starting at index 1, removed all the other elements and also mutated the original Array.

Specifying the second argument, allows us to control how many items are removed from the Array.

const myArray = ['zero', 'one', 'two', 'three'];

// Remove 2 items starting at index 1.
const removed = myArray.splice(1, 2);

console.log(removed);  //        one', 'two'
console.log(myArray);  // 'zero',           'three'

Adding new items with splice()

We can add new items to an existing Array using splice() by specifying 0 as the number of items to delete and more items after the second parameter.

const myArray = ['zero', 'one', 'two', 'three'];

// Add 'four' and 'five' after the item with the index 3 ('three')
const removed = myArray.splice(4, 0, 'four', 'five');

console.log(removed);  // [empty array]
console.log(myArray);  // 'zero', 'one', 'two', 'three', 'four', 'five'

Updating existing items with splice()

We can update items in an Array using splice() by specifying the start index, the number of items to delete and finally the items that should replace the deleted items.

const myArray = ['zero', 'one', 'two', 'three'];

// Delete one item starting at index 2 ('two')
// and in its place insert the number 2
const removed = myArray.splice(2, 1, '2');

console.log(removed);  // 'two'
console.log(myArray);  // 'zero', 'one', '2', 'three'

The example above is updating a single item, but we can also batch update items if they’re sequential.

const myArray = ['zero', 'one', 'two', 'three'];

// Delete 3 items starting at index 1 ('one', 'two', 'three')
// and in their place insert 1, 2, 3
const removed = myArray.splice(1, 3, '1', '2', '3');

console.log(removed);  // 'one', 'two', 'three'
console.log(myArray);  // 'zero', '1', '2', '3'

Conclusion

That’s it! I really hope my short explanation of how both slice() and splice() work have helped you. If there are any unclarities, or if you think that I’ve missed certain details, please let me know in the comments below.

Subscribe

Be the first to know when I publish a new article on the blog.

No spam. You can unsubscribe at any time.


Comments