slice vs splice in JavaScript arrays
Intermediate · 3 min read
slice and splice are two array methods one letter apart that do almost opposite things. slice copies part of an array and leaves the original alone. splice cuts items out of the original, can put new items in, and hands you back the pieces it cut. Mixing them up is one of the most common array bugs, because the code still runs.
In this tutorial you will copy the middle of an array with slice, remove the middle with splice, insert with splice, and pay close attention to what each one returns. You should know arrays and indexes. Half-open ranges and mutating are explained below.
Half-open ranges
slice(start, end) uses a half-open range: it includes start and stops just before end. So slice(1, 3) gives indexes 1 and 2, and end - start is how many items you get.
Copy or change?
A method that changes the array you call it on is said to mutate it. slice never mutates. splice always does. That single fact explains almost everything below.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
15 slice against splice
fairCopy the middle of an array with slice, then remove the middle with splice. Pay attention to what each one returns.
Stuck? Three hints, smallest first
- 1.
slice(start, end)copies a half-open range and never changes the original. - 2.
splice(start, count, ...insert)mutates, and returns the elements it took out. - 3. So
const shorter = xs.splice(1, 2)almost certainly does not do what the name says.
Step 1: copy the middle with slice
const source = [1, 2, 3, 4, 5];
const sliced = source.slice(1, 3);
console.log(sliced); // [ 2, 3 ]
console.log(source); // [ 1, 2, 3, 4, 5 ]
You get a new array with indexes 1 and 2. source is untouched.
Step 2: more ways to slice
const source = [1, 2, 3, 4, 5];
console.log(source.slice(-2)); // [ 4, 5 ]
console.log(source.slice(3)); // [ 4, 5 ]
console.log(source.slice()); // [ 1, 2, 3, 4, 5 ]
console.log(source.slice() === source); // false
A negative start counts back from the end, so slice(-2) is the last two. With only a start, it goes to the end. With no arguments at all, you get a copy of the whole array: a different array with the same items, which is why === says false.
Step 3: remove the middle with splice
splice(start, count) removes count items starting at start. Watch what it returns.
const spliceTarget = [1, 2, 3, 4, 5];
const removed = spliceTarget.splice(1, 2);
console.log(removed); // [ 2, 3 ]
console.log(spliceTarget); // [ 1, 4, 5 ]
The second argument is a count, not an end index like slice has. splice changed spliceTarget itself, and its return value is the items it took out, not the shorter array.
Step 4: the wrong turn
Because of that return value, this line reads well and does the wrong thing:
const xs = [1, 2, 3, 4, 5];
const shorter = xs.splice(1, 2);
console.log(shorter); // [ 2, 3 ]: the bits that were cut out
console.log(xs); // [ 1, 4, 5 ]: the array you wanted
shorter holds the offcuts, and xs has been changed without the name saying so. With splice, the answer you want is usually the array you called it on.
Step 5: insert with splice
Every argument after the count is an item to insert at start. A count of 0 removes nothing, so splice becomes a pure insert.
const inserted = [1, 2, 3];
const nothingRemoved = inserted.splice(1, 0, 'x', 'y');
console.log(nothingRemoved); // []
console.log(inserted); // [ 1, 'x', 'y', 2, 3 ]
Nothing was removed, so the return value is an empty array. The new items went in at index 1, and everything after moved along.
Step 6: replace in one call
Removing and inserting at once makes a swap:
const stops = ['Yaba', 'Mushin', 'Oshodi'];
stops.splice(1, 1, 'Surulere');
console.log(stops); // [ 'Yaba', 'Surulere', 'Oshodi' ]
This is the one thing only splice can do among the classic methods: remove and insert in place, in one step. When you need the same result without changing the original, the next exercise shows how to build copies with slice and spread.
The full solution
The panel slices a copy, splices a second array, inserts into a third, and prints every return value next to the array after the call. Press Run and compare them.
const source = [1, 2, 3, 4, 5];
const sliced = source.slice(1, 3);
const spliceTarget = [1, 2, 3, 4, 5];
const removed = spliceTarget.splice(1, 2); // returns what it removed
const inserted = [1, 2, 3];
const nothingRemoved = inserted.splice(1, 0, 'x', 'y'); // insert only
console.log('slice(1, 3) :', sliced, ' source still:', source);
console.log('splice(1, 2) :', removed, '<- the REMOVED elements');
console.log('the array after :', spliceTarget);
console.log("splice(1, 0, 'x', 'y'):", nothingRemoved, '<- nothing removed');
console.log('the array after :', inserted);
console.log('slice(-2) :', source.slice(-2));
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('slice copies a half-open range', sliced, [2, 3]);
test('and leaves the source untouched', source, [1, 2, 3, 4, 5]);
test('slice() with no arguments copies the whole thing', source.slice(), [1, 2, 3, 4, 5]);
test('but the copy is a different array', source.slice() === source, false);
test('a negative start counts back from the end', source.slice(-2), [4, 5]);
test('splice returns the elements it removed', removed, [2, 3]);
test('and shortens the array it was called on', spliceTarget, [1, 4, 5]);
test('a count of 0 removes nothing, so it returns an empty array', nothingRemoved, []);
test('while the insertion happened in place', inserted, [1, 'x', 'y', 2, 3]);
Two methods one letter apart, doing opposite things. slice is a copy and its return value is the answer. splice is an edit and its return value is the offcut — the array you wanted is the one you called it on. Writing const trimmed = xs.splice(0, 3) gives you the first three elements while quietly destroying xs.
splice is also the only built-in that removes and inserts at once, which is genuinely useful: xs.splice(i, 1, replacement) swaps one element in place. When you want that without mutating, exercise 16 has the copying versions.
Common mistakes
- Treating
splice's return value as the new array. It returns the removed items. The edited array is the one you called it on. - Giving
splicean end index. Its second argument is a count.slice(1, 3)andsplice(1, 3)cover different items. - Calling
spliceon an array other code shares. Everyone holding that array sees the change. Usesliceand spread to build a new array instead.
Try it yourself
- Use
sliceto get the first three items of['a', 'b', 'c', 'd', 'e']. - Use
spliceto remove the last item of an array, and print what it returns. - Use
spliceto insert'tea'at the start of['milk', 'sugar'].