Array splice(): insert and remove
Quick answer
Splice changes an array by deleting, inserting or replacing values at a position. It returns a separate array of removed values.
How it works
items.splice(start, deleteCount, ...itemsToInsert) mutates the source. A negative start counts from the end; deleteCount zero inserts without deleting. If only start is supplied, removal continues to the end. Passing undefined as deleteCount is different from omitting it.
const a = [1, 2, 3];const removed = a.splice(1, 1, 8, 9);console.log(removed[0], a.length, a[1], a[2]);Expected output in Node.js:
2 4 8 9One value is replaced with two.
const a = ["a", "c"];a.splice(1, 0, "b");console.log(a[0], a[1], a[2]);Expected output in Node.js:
a b cA zero deletion count inserts between existing values.
Common mistakes
The returned array is the removed range, not the updated source. If mutation is unwanted, make a shallow copy before calling splice.
Practice
Replace the second task in a three-task array, then insert a task without deleting.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Array splice(): insert and remove — Knowledge Check
Apply the taught concept and reason about the result.
What does splice return?
What happens to a=[1,2,3] after a.splice(1,1,9)?
What does a.splice(1,0,"x") do?
What does [1,2,3].splice(1) return?
Which method is appropriate for selecting a range without mutating the source?