JavaScriptArrays

Array.prototype.toSpliced()

Removes, inserts, or replaces elements in a copy of the array. The original is left unchanged.

Returns
A new array after the changes.
Changes the original
No
On this page

Example

#
JavaScript
const plan = ['HTML', 'CSS', 'PHP', 'JavaScript']

const updated = plan.toSpliced(2, 1, 'Sass')
console.log(updated)
console.log(plan)
Console
['HTML', 'CSS', 'Sass', 'JavaScript']
['HTML', 'CSS', 'PHP', 'JavaScript']

Definition and usage

#

The toSpliced(start, skipCount, ...items) method works like splice(), but instead of changing the array, it returns a new, already-modified one. Starting at index start, it skips skipCount elements and inserts the given values in their place. The original array doesn’t change.

An important difference is in the result: splice() returns the array of removed elements, while toSpliced() returns the whole new array. If you also need the removed elements, read them beforehand with slice().

With a single call you can remove an element (toSpliced(i, 1)), insert a new one without removing anything (toSpliced(i, 0, x)), or swap a chunk for other values. A negative start counts its position from the end. The method belongs to the family of copying methods, together with toSorted(), toReversed(), and with().

Syntax

#
Syntax
array.toSpliced(start)
array.toSpliced(start, skipCount)
array.toSpliced(start, skipCount, item1, item2, …)

Parameters

#
  • start

    number

    The index the changes start at. A negative value counts from the end.
  • skipCount

    optional

    The number of elements left out of the copy. Omitted means everything from start to the end.
  • item1…itemN

    optional

    The elements inserted into the copy at start.

More examples

#
Removing and inserting
JavaScript
const queue = ['Emma', 'Jack', 'Mia']

console.log(queue.toSpliced(1, 1))
console.log(queue.toSpliced(1, 0, 'Sophie'))
console.log(queue.toSpliced(-1))
Console
['Emma', 'Mia']
['Emma', 'Sophie', 'Jack', 'Mia']
['Emma', 'Jack']
splice() vs. toSpliced() result
JavaScript
const tasks = ['Quiz', 'Project', 'Test']

const copy = tasks.toSpliced(0, 1)
const removed = tasks.splice(0, 1)

console.log(copy)
console.log(removed)
console.log(tasks)
Console
['Project', 'Test']
['Quiz']
['Project', 'Test']

toSpliced() handed back a new array and left tasks alone. Only splice() changed the original, returning what it removed from it.

Browser support

#

Widely available · since 2023

Works in all modern browsers, phones included. You can use it without worry.

  • Chrome
  • Edge
  • Firefox
  • Safari

Good practices

#
  • To remove an element by index, for example in React component state, items.toSpliced(index, 1) is enough. You don’t need a spread copy or a filter() that compares indexes.
  • Don’t mix up the results: toSpliced() returns a new array, while splice() returns the array of removed elements.

Related entries

#

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