ComparisonComparisons

slice() vs splice()

slice() copies a section of the array without changing the original, while splice() removes, inserts, or replaces elements in place, mutating the array.

On this page

Side-by-side comparison

#

Example

#
JavaScript
const modules = ['Intro', 'HTML', 'CSS', 'Grid']

const copy = modules.slice(1, 3)
const removed = modules.splice(1, 1)

console.log(copy)
console.log(removed)
console.log(modules)
Console
['HTML', 'CSS']
['HTML']
['Intro', 'CSS', 'Grid']

Definition and usage

#

The names look deceptively alike, but the methods do different things. slice(start, end) cuts out a section of the array and returns it as a new array, without touching the original. splice(start, deleteCount, ...items) changes the original array: it removes the given number of elements starting at start, and can insert new ones in their place.

slice() always returns the section it cut out, while splice() returns the elements it removed (which can be an empty array, when nothing was removed). Negative indexes count from the end of the array in both methods. Only splice() accepts extra arguments with elements to insert.

The choice depends on whether you want to keep the original. Use slice() for copying, pagination, and sections. Use splice() to remove or insert an element at a specific spot, and if you don’t want to mutate the array, reach for its newer counterpart toSpliced().

Syntax

#
Syntax
array.slice(start, end)
array.splice(start, deleteCount, item1, item2, …)

More examples

#
splice() for inserting, slice() for previewing the tail
JavaScript
const list = ['HTML', 'CSS', 'JavaScript']

list.splice(1, 0, 'Sass')
console.log(list)
console.log(list.slice(-2))
Console
['HTML', 'Sass', 'CSS', 'JavaScript']
['CSS', 'JavaScript']
slice() doesn’t mutate, even in edge cases
JavaScript
const original = ['Emma', 'Jack']

const sliced = original.slice()
const splicedResult = original.splice(5, 2)

console.log(sliced)
console.log(splicedResult)
console.log(original)
console.log(sliced === original)
Console
['Emma', 'Jack']
[]
['Emma', 'Jack']
false

splice() outside the array’s range removes nothing and returns an empty array. slice() with no arguments creates a shallow copy, but it’s a different object than the original.

Good practices

#
  • slice() never mutates, so it’s safe for copies and pagination even inside functions that shouldn’t change their input data.
  • When removing elements with splice() in a loop, go from the end of the array. Going from the start, the remaining indexes shift and it’s easy to skip something.
  • When you need the effect of splice() but without mutating the original, use toSpliced().

Related entries

#

Spotted a mistake or missing an example? Write to us.