What does splice() do?
It can remove, add and replace elements right in the original array.
Syntax
javascript
array.splice(start, deleteCount, item1, item2, ...);| Parameter | What it does |
|---|---|
start | The index at which changes start |
deleteCount | How many elements to remove |
item1, item2, ... | Elements to insert in place of the removed ones (optional) |
1. Removing elements
javascript
const arr = ["a", "b", "c", "d"];
const removed = arr.splice(1, 2);
console.log(arr); // ["a", "d"]
console.log(removed); // ["b", "c"]- From position
1, remove2elements. - Returns an array of the removed elements.
- The original array is changed.
2. Adding elements
javascript
const arr = ["a", "d"];
arr.splice(1, 0, "b", "c");
console.log(arr); // ["a", "b", "c", "d"]deleteCount = 0means nothing is removed.- We add
"b"and"c"at position1. - Everything that came after shifts to the right.
3. Replacing elements
javascript
const arr = ["a", "b", "c"];
arr.splice(1, 1, "x", "y");
console.log(arr); // ["a", "x", "y", "c"]- Starting at index
1, remove1element ("b") - and insert
"x","y"in its place. - You can think of this as removal + insertion at the same time.
4. Using negative indexes
javascript
const arr = [1, 2, 3, 4];
arr.splice(-2, 1); // remove one element starting from the end
console.log(arr); // [1, 2, 4]-2 means "the second element from the end".
5. If you remove more than exists
javascript
const arr = [1, 2];
arr.splice(1, 10);
console.log(arr); // [1]The method does not throw an error, it just removes everything there is starting from position 1.
In short:
| What it does | Example | Result |
|---|---|---|
| Removes | arr.splice(1, 2) | Removes 2 elements starting at index 1 |
| Adds | arr.splice(2, 0, "x") | Inserts "x" at position 2 |
| Replaces | arr.splice(1, 1, "x") | Changes 1 element to "x" |
| Returns | ["removed elements"] | array of removed values |
| Mutates the original array | Yes |
An "all at once" example
javascript
const arr = [1, 2, 3, 4, 5];
// remove 2 elements starting at index 1 and insert new ones
const removed = arr.splice(1, 2, "a", "b", "c");
console.log(arr); // [1, "a", "b", "c", 4, 5]
console.log(removed); // [2, 3]Summary:
splice()is a universal "Swiss army knife" for arrays: it removes, adds and replaces elements right in the original array and returns an array of the removed values.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.