Explain Codes LogoExplain Codes Logo

Javascript Array splice vs slice

javascript
array-methods
javascript-performance
best-practices
Alex KataevbyAlex Kataev·Feb 26, 2025
TLDR

.splice() modifies the original array, accommodating removal, insertion, or replacement of elements. Example:

let nums = [1, 2, 3, 4]; nums.splice(2, 1, 'a'); // Path opened at index 2, the number 3 vanished, 'a' strolled in // nums is now [1, 2, 'a', 4]

.slice() crafts a new array from chosen elements, keeping the original as pristine as ever. Example:

let nums = [1, 2, 3, 4]; let newNums = nums.slice(1, 3); // Operating table set from index 1 to 3. No nums were harmed. // newNums birthed as [2, 3], nums remains unscathed

The nuts and bolts

The cryptic parameters decoded

The parameters for .splice() are start index, deleteCount (optional), and the items to add (optional). For .slice(), start is where to kick off the selection, end index (optional) ends the party early (and it's always one step ahead, or exclusive).

  • Use splice to 'vanish' elements: array.splice(start, deleteCount)
  • Use splice to plant elements without causing any disappearances: array.splice(start, 0, newItem1, newItem2, ...)
  • Use slice to 'clone' a segment: array.slice(start, end)

Caution: The splice deletion count indicates the number of guests leaving the party, not the ending index.

These are test-drive results, believe it!

Here's how you navigate the crossroads:

  • Need to fax a copy without bulldozing the original? .slice() is at your service.
  • Got some elements to bid farewell to or new ones to welcome? .splice() can work both ways.

Pro Tip: Always sneak a peek at the original array after invoking these methods to avoid unexpected plot twists.

Dodging common traps

  1. Don't mix splice's deleteCount with slice's end index.
  2. Note that splice can pull the good cop (add) as well as the bad cop (remove) role.
  3. Understand that slice does a 'ctrl+C & ctrl+V' gesture, keeping object references intact.

Confirm outcomes with good ol' console.log tests to keep these traps at bay.

Let's break down the elements

Adding vs removing: be the director

Write your own script with these methods:

  • Removing elements: Use splice to host a goodbye party for the elements you no longer need.
  • Adding elements: Use splice as your recruitment tool, placing new elements wherever your heart desires.
  • Copying segments: When you need a good cameo without bothering the entire cast, slice is your go-to method.

From abstract to concrete

Picture an inventory warehouse. Out of stock items? splice them out. New stock deluge? splice them in. Need an inventory check without triggering an event? slice out the relevant section.

Caring about performance

Bear these in mind:

  • As splice rearranges elements, it may demand extra memory.
  • For duplicating jobs, slice is often faster as it doesn't stress about the original array.

These inferences can help optimise your coding approach.