JavaScript splice(): Add, Remove, and Replace Array Elements

Learn JavaScript splice() with examples to remove, add, and replace array elements, understand mutation, return values, and slice vs splice.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

JavaScript splice(): Add, Remove, and Replace Array Elements

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

javascript
array.splice(start, deleteCount, item1, item2)
Output

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

javascript
const letters = ["a", "b", "c", "d"];

console.log("splice-removed:", letters.splice(1, 2, "x", "y").join(","));
console.log("splice-array:", letters.join(","));
Output

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

javascript
const items = ["a", "b", "c"];
const removed = items.splice(1, 1);

console.log(removed);
console.log(items);
Output

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

javascript
const items = ["a", "d"];
items.splice(1, 0, "b", "c");

console.log(items);
Output

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

javascript
const items = ["a", "b", "c", "d"];
items.splice(-1, 1);

console.log(items);
Output

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.


Official Documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …