splice() changes an array by removing, replacing, or inserting elements. It mutates the original array and returns an array of removed elements.
Use splice() when you intentionally want to edit the source array. Use slice() when you only want a copied section without changing the original.
Environment: Node.js v20.18.2. After each runnable snippet, the following paragraph states the expected console output (order and values).
JavaScript splice Syntax
array.splice(start, deleteCount, item1, item2)start is the index where changes begin. deleteCount is the number of elements to remove. Additional items are inserted at the start position.
Method 1: Remove and Replace Elements
const letters = ["a", "b", "c", "d"];
console.log("splice-removed:", letters.splice(1, 2, "x", "y").join(","));
console.log("splice-array:", letters.join(","));You should see 2 lines, in order: splice-removed: b,c, splice-array: a,x,y,d.
splice() removed b and c, then inserted x and y at index 1.
Method 2: Remove Elements Only
const items = ["a", "b", "c"];
const removed = items.splice(1, 1);
console.log(removed);
console.log(items);You should see 2 lines, in order: [ 'b' ], [ 'a', 'c' ].
The removed elements are returned as a new array.
Method 3: Insert Elements Without Removing
const items = ["a", "d"];
items.splice(1, 0, "b", "c");
console.log(items);You should see one line logging [ 'a', 'b', 'c', 'd' ].
A deleteCount of 0 inserts items without deleting anything.
Method 4: Use Negative Start Index
const items = ["a", "b", "c", "d"];
items.splice(-1, 1);
console.log(items);You should see one line logging [ 'a', 'b', 'c' ].
Negative indexes count from the end of the array.
Common Questions About JavaScript splice
Does splice mutate the original array?
Yes. splice() changes the original array.
What does splice return?
It returns an array containing the removed elements.
What is the difference between slice and splice?
slice() copies without changing the original array. splice() edits the original array.
Summary
Use JavaScript splice() to remove, insert, or replace array elements in place. It starts at a chosen index, removes deleteCount elements, optionally inserts new items, and returns the removed elements. For non-mutating extraction, use slice() instead.
