Skip to content
jshacks.dev
Fundamentals

JavaScript Array splice Explained Step by Step With Code

Array splice() removes, inserts and replaces items in place and returns the removed ones. See the one-argument trap, negative start and loop pitfalls.

7 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, Vite, Node.js and TypeScript logos.

splice() does three jobs with one signature, and the signature has a quirk that deletes more than people intend: pass only a start index and everything from there to the end is removed. Pass -1 as the start when an earlier indexOf() found nothing, and it removes the last element instead of nothing. The return value is also the opposite of what a newcomer expects, since it hands back the removed items and not the edited array. This post covers the three arguments, removal, insertion and replacement, negative starts, the argument-count rule, the cost and shape of the return value, loops that skip items, and when toSpliced() or slice() is the better choice. Everything runs on Node.js 24. The copy-first sibling is in [the post on toSpliced()](/library/javascript-array-tospliced), and the non-mutating range copy is [slice()](/library/javascript-array-slice).

What splice() takes and returns

The signature is array.splice(start, deleteCount, item1, item2, ...). It removes deleteCount elements beginning at start, inserts the given items at that spot, and returns an array of the removed elements. The array is changed in place.

ArgumentMeaningNotes
startIndex where the change beginsNegative counts from the end, clamped to the array
deleteCountHow many elements to removeOptional, see the rules below
item1, item2, ...Elements to insert at startOptional
Return valueArray of removed elementsEmpty array if nothing was removed
Call shapeEffect
splice(i, n)Remove n items at i
splice(i, 0, x)Insert x at i, removing nothing
splice(i, n, x)Replace n items with x
splice(i)Remove everything from i to the end
splice()Do nothing and return []

Removing items

The return value is the removed slice, which makes it easy to move items between lists.

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

const removed = letters.splice(1, 2);

console.log(removed);
console.log(letters);
Text
[ 'b', 'c' ]
[ 'a', 'd', 'e' ]

Two items starting at index 1 were taken out and returned, and the remaining items closed the gap. If you want the edited array, read the variable. The call's return value is the removed part.

Inserting and replacing

A deleteCount of 0 inserts without removing anything. Providing items with a nonzero count replaces.

JavaScript
const list = ["a", "d"];

list.splice(1, 0, "b", "c");
console.log(list);

const replaced = list.splice(0, 1, "A");
console.log(replaced);
console.log(list);
Text
[ 'a', 'b', 'c', 'd' ]
[ 'a' ]
[ 'A', 'b', 'c', 'd' ]

The first call inserted two items at index 1 and removed none. The second removed "a" and put "A" in its place, returning the removed element in a one-item array. The number of inserted items does not need to match deleteCount, so the array can grow or shrink.

The one-argument rule

When you pass only start, the method removes everything from there to the end. When you pass start and an explicit undefined for deleteCount, it removes nothing, because undefined converts to 0. The two cases look similar and behave oppositely.

JavaScript
const a = [1, 2, 3, 4, 5];
const b = [1, 2, 3, 4, 5];

console.log(a.splice(2));
console.log(a);

console.log(b.splice(2, undefined));
console.log(b);
Text
[ 3, 4, 5 ]
[ 1, 2 ]
[]
[ 1, 2, 3, 4, 5 ]

The specification checks how many arguments were passed, not their values. This is a real source of bugs when a helper forwards (start, count) and the count is sometimes undefined: the intent was "to the end", and the result is "nothing". Handle that case explicitly, for example by passing array.length - start.

Negative and out-of-range starts

A negative start is an offset from the end. A start larger than the length is clamped to the length, so the call becomes an append.

JavaScript
const items = ["a", "b", "c", "d"];

console.log(items.splice(-2, 1));
console.log(items);

items.splice(99, 0, "z");
console.log(items);
Text
[ 'c' ]
[ 'a', 'b', 'd' ]
[ 'a', 'b', 'd', 'z' ]

splice(-2, 1) removed the second-to-last item. The call with 99 did not throw: the start clamped to the end and the insert acted like push(). Out-of-range values are never errors, which is convenient and also hides mistakes in computed indexes.

The indexOf minus one trap

Removing a value by finding its index first is the standard recipe. It has one fatal omission: when the value is absent, indexOf() returns -1, and splice(-1, 1) removes the last element.

JavaScript
const tags = ["red", "green", "blue"];

tags.splice(tags.indexOf("pink"), 1);

console.log(tags);
Text
[ 'red', 'green' ]

"pink" is not in the list and "blue" was removed anyway. Guard the call:

JavaScript
const tags2 = ["red", "green", "blue"];
const at = tags2.indexOf("pink");

if (at !== -1) {
  tags2.splice(at, 1);
}

console.log(tags2);
Text
[ 'red', 'green', 'blue' ]

Our team treats an unguarded splice(indexOf(...), 1) as a review failure on sight. The post on removing an item by value compares this approach with filter().

Splicing while looping

Removing items from the array you are iterating shifts the indexes under the loop, so the next element is skipped.

JavaScript
const nums = [1, 2, 2, 3, 2];

for (let i = 0; i < nums.length; i++) {
  if (nums[i] === 2) nums.splice(i, 1);
}

console.log(nums);
Text
[ 1, 2, 3 ]

Three 2s went in and one is left. When index 1 was removed, the second 2 slid into index 1, and the loop moved to index 2, skipping it. Looping backward avoids the problem, because removals only shift items that were already visited.

JavaScript
const nums2 = [1, 2, 2, 3, 2];

for (let i = nums2.length - 1; i >= 0; i--) {
  if (nums2[i] === 2) nums2.splice(i, 1);
}

console.log(nums2);
Text
[ 1, 3 ]

For a simple removal, nums.filter((n) => n !== 2) is shorter and has no index to get wrong. Use splice() in the loop when you must keep the same array object for other code that holds a reference to it.

Holes and array-likes

Holes are preserved when they sit outside the changed range and move with the elements.

JavaScript
const sparse = [1, , 3, 4];

const removed = sparse.splice(0, 2);

console.log(removed);
console.log(sparse);
Text
[ 1, <1 empty item> ]
[ 3, 4 ]

The removed array keeps the hole as a hole. Like the other mutators, the method is generic, so Array.prototype.splice.call(obj, ...) works on an object with a numeric length, though modern code seldom needs it.

A mistake we hit: a forwarded count that was undefined

A pagination helper wrapped splice() to trim a queue, taking an optional limit.

JavaScript
function trim(queue, from, limit) {
  return queue.splice(from, limit);
}

const q1 = ["a", "b", "c", "d"];
const q2 = ["a", "b", "c", "d"];

console.log(trim(q1, 1, 2));
console.log(trim(q2, 1));
console.log(q2);
Text
[ 'b', 'c' ]
[]
[ 'a', 'b', 'c', 'd' ]

The second call reached splice() with limit as an explicit undefined, which still counts as an argument, so nothing was removed. The caller expected "from index 1 to the end". The fix is to branch on the argument:

JavaScript
function trimFixed(queue, from, limit) {
  const count = limit === undefined ? queue.length - from : limit;
  return queue.splice(from, count);
}

const q3 = ["a", "b", "c", "d"];

console.log(trimFixed(q3, 1));
console.log(q3);
Text
[ 'b', 'c', 'd' ]
[ 'a' ]

splice() compared with its neighbors

MethodMutatesReturnsUse when
splice()YesThe removed itemsYou edit the array in place
toSpliced()NoThe edited copyYou need the result and the original
slice()NoA range copyYou only read a part
filter()NoNew array of kept itemsYou remove by condition
push() and pop()YesLength or elementThe change is at the end

Reading the return value

Because the return value is the removed items, splice() is useful for moving elements between arrays. Taking a batch off the front of a work list is one call, batch = work.splice(0, 10), which removes up to ten items and hands them to you, leaving the rest in work. If fewer than ten remain, you get what is left, and a later call returns an empty array, so a loop can run until the returned array is empty. That makes the method a compact way to chunk a list in place, and it is the reason splice() still has a role next to the newer copying methods.

The cost is that you have to keep track of two things at once: the array that was edited and the array that was returned. In code review, we ask for names that say which is which, such as removed for the return and the original variable for the remainder. If you find yourself needing both the edited array and the removed items as separate immutable values, compute the removed part with slice() and the edited part with toSpliced(), as the later sections show, so neither value depends on a side effect.

One last detail is length. After a splice, the array's length is already updated, so loops that use array.length as their condition see the new size immediately. That is the source of the skipping bug shown above, and it is also what makes while (queue.length) loops with splice(0, n) work without any bookkeeping.

Where splice stops being the right tool

splice() stops being right when the array is shared or immutable by convention, since it edits in place and returns the wrong thing for chaining. In that case toSpliced() from ES2023, available in Node.js 24, returns the edited copy. It also stops being right for removal by condition, which filter() says directly, and for removing from the ends, where shift(), pop(), push() and unshift() are clearer.

Performance is a mechanism, not a number: inserting or removing in the middle moves every later element, so a large array edited repeatedly pays that move each time. If you do that in a hot loop, collect the changes and rebuild once, or use a different structure.

The method is specified as Array.prototype.splice and documented by MDN on the Array.prototype.splice page.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.