JavaScript Array Manipulation: slice() vs. splice()

Hero image for JavaScript Array Manipulation: slice() vs. splice(). Image by Jason Leung.
Hero image for 'JavaScript Array Manipulation: slice() vs. splice().' Image by Jason Leung.

JavaScript provides a rich set of tools for working with arrays, amongst which slice() and splice() are particularly versatile yet often very easy to confuse. While both methods deal with array elements (and their names are only one character apart), their purposes and effects are very different.

Here I intend to help add a little clarity to these two methods, highlight their differences, and explain why misusing them can lead to issues in your code...


What is slice?

I've written about slice() in detail before, but to give a quick overview for the sake of comparisons: slice() is a method used to return a shallow copy of a portion of an array into a new array object. It does not modify the original array but instead creates a new one.

slice() syntax

arr.slice([begin[, end]])
  • begin (optional): Zerobased index at which to begin extraction.
  • end (optional): Zerobased index before which to end extraction.

An Example in Code

const numbers = [1, 2, 3, 4, 5];const sliced = numbers.slice(1, 4);console.log(sliced);  //=> [2, 3, 4]console.log(numbers);  // Original array remains unchanged

What is splice()?

splice(), on the other hand, changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. It is destructive; it alters the original array. I've written about splice() in detail before too, but it bears summarising for the sake of comparing it against slice().

splice() syntax

arr.splice(start[, deleteCount[, item1[, item2[, ...]]]])
  • start: Index at which to start changing the array.
  • deleteCount (optional): Number of elements to be removed.
  • item1, item2, ... (optional): Elements to add to the array.

An Example in Code

const numbers = [1, 2, 3, 4, 5];numbers.splice(2, 1, 'a', 'b');console.log(numbers);  //=> [1, 2, 'a', 'b', 4, 5]

You'll hopefully notice here at splice() has modified the original numbers variable, this is an important difference.


Key Differences

1. Modification of the Original Array:

  • slice() does not alter the original array; it returns a new array.
  • splice() modifies the original array, either adding, removing, or replacing elements.

2. Return Value:

  • slice() returns a new array containing the extracted elements.
  • splice() returns an array of the removed elements (if any).

3. Purpose:

  • slice() is primarily used for extracting a subarray.
  • splice() is used for more complex array operations like inserting, deleting, or replacing elements.

Why the Confusion?

I wrote some time ago that I felt slice() and splice() were some of the more commonly misunderstood aspects of JavaScript things I see most frequently when doing code reviews or mentoring. It's fair to say that as they stand alone, they both have confusing aspects (which I've also written about in more detail before).

Nevertheless, it is not uncommon to also see confusion specifically between the use of slice() and splice(). I personally feel that a lot of this confusion often simply stems from their similarsounding names and the fact that they both deal with arrays. They do however also have superficially similar syntax and uses, which can only confuse things further.


Potential Issues from Misuse

Because of that similarlooking syntax, it is actually possible to use splice in place of slice (or vice versa) and introduce bugs without even really realising what or why it is happening. The most common issues this misuse cam lead to include:

  • Unintended side effects

    : Since splice() modifies the original array, it can lead to bugs where the original array's state is unexpectedly altered.
  • Incorrect results

    : Using slice() in a situation that requires splice() (or the other way around) will not produce the desired outcome, although it might just look close enough to get past even a seasoned developer, leading to errors in the codebase.

Wrapping‑Up

Understanding the differences between slice() and splice() is crucial for any JavaScript developer. These methods, whilst powerful, serve different purposes and have different impacts on arrays. A clear understanding of these differences helps prevent common bugs and ensures more robust array manipulation in your applications.


Categories:

  1. Development
  2. Front‑End Development
  3. Guides
  4. JavaScript