Difference between slice() and splice()?

slice(start, end) returns a copy of part of an array without changing it; splice(start, deleteCount, ...items) changes the original array in place by removing and/or inserting items, and returns the removed ones.

slicesplice
Mutates originalNoYes
ReturnsNew array with the selected partArray of removed items
end / countEnd index (exclusive)How many items to remove
Also on stringsYes ("hello".slice(1, 3))No

slice details

  • Negative indexes count from the end: arr.slice(-2) gives the last two items.
  • arr.slice() with no arguments makes a shallow copy.

splice details

  • Remove: arr.splice(1, 2) removes two items starting at index 1.
  • Insert: arr.splice(1, 0, "x") inserts without removing.
  • Replace: arr.splice(1, 1, "x") swaps one item.

Immutable alternative: toSpliced (ES2023)

arr.toSpliced(1, 1, "x") does what splice does but returns a new array and leaves the original alone. This is what you want for React state, where mutating with splice would not trigger a re-render.

Memory trick

splice = changes in place.

Code example

js
1const letters = ["a", "b", "c", "d", "e"];
2
3// slice: copy part of the array, original unchanged
4console.log(letters.slice(1, 3)); // ["b", "c"]
5console.log(letters.slice(-2)); // ["d", "e"]
6console.log(letters); // ["a", "b", "c", "d", "e"]
7
8// splice: modifies in place, returns removed items
9const removed = letters.splice(1, 2); // remove 2 items at index 1
10console.log(removed, letters); // ["b", "c"] ["a", "d", "e"]
11
12letters.splice(1, 0, "x", "y"); // insert without removing
13console.log(letters); // ["a", "x", "y", "d", "e"]
14
15letters.splice(-1, 1, "z"); // replace the last item
16console.log(letters); // ["a", "x", "y", "d", "z"]
17
18// Immutable splice for state updates
19const todos = ["write", "test", "ship"];
20const withoutTest = todos.toSpliced(1, 1);
21console.log(withoutTest, todos); // ["write", "ship"] ["write", "test", "ship"]
22
23// slice works on strings too
24console.log("JavaScript".slice(0, 4)); // Java

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app