Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.prototype.splice

Removes, replaces or inserts elements in the middle of an array.

Available since: ES3

Syntax

array.splice(start, deleteCount, item1, /* … */)

Parameters

ParameterTypeDescription
startnumberThe position where the change starts. A negative one counts from the end.
deleteCountnumberOptional. How many elements to remove. All the rest by default.
item1, …anyOptional. Elements to insert in place of the removed ones.

Return value

ArrayAn array of the removed elements.

Examples

Removing one element at an index:

const letters = ['a', 'b', 'c', 'd'];
letters.splice(1, 1);
 
console.log(letters);

Output:

[
  "a",
  "c",
  "d"
]

Inserting without removing — deleteCount is 0:

const letters = ['a', 'd'];
letters.splice(1, 0, 'b', 'c');
 
console.log(letters.join(''));

Output:

abcd

Replacing and getting the removed part:

const letters = ['a', 'b', 'c'];
const removed = letters.splice(1, 2, 'X');
 
console.log(removed.join(''), letters.join(''));

Output:

bc aX

Notes

Do not confuse it with slice(): splice() changes the original array, slice() does not. The non-mutating version is toSpliced().

See also

Related recipes

In the tutorial

  • Array methods — How to add and remove array elements in JavaScript: push, pop, shift, unshift, slice, splice, concat and join.

Thanks for reading!

Donate to the site — we work hard for you.