Online Compiler logoOnline Compiler

JavaScript Tutorial

JavaScript slice() and splice()

slice copies part of an array without changing it, while splice edits the array in place.

Knowing the difference prevents mutation bugs.

Why We Need It

Many bugs come from unintentional array mutation.

Choosing the right method keeps your data flow predictable.

Syntax

array.slice(start, end)
array.splice(start, deleteCount, ...items)

Basic Example

1. slice

const items = ["a", "b", "c", "d"];
const part = items.slice(1, 3);

console.log(part); // ["b", "c"]
console.log(items); // unchanged

slice copies without mutation.

Real World Example

2. splice remove

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

console.log(items); // ["a", "d"]

splice removes items in place.

Multiple Use Cases

slice = copy

slice returns a shallow copy of a portion of the array.

It does not modify the original array.

splice = edit

splice removes or inserts items in place.

It mutates the original array.

When to Use

Use slice when you want immutability.

Use splice when you must update the array itself.

More Examples

3. splice insert

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

console.log(items); // ["a", "b", "c", "d"]

splice can insert items.

4. slice with negative

const items = ["a", "b", "c", "d"];
const lastTwo = items.slice(-2);

console.log(lastTwo); // ["c", "d"]

Negative indexes count from the end.

Comparison

Without

const items = [1, 2, 3];
items.splice(1, 1); // mutates

With

const items = [1, 2, 3];
const copy = items.slice(1, 2); // no mutation

Common Mistakes and Fixes

Using slice when you need mutation

Use splice to change the original array.

Using splice when you need immutability

Use slice to copy instead of mutate.

Forgetting splice returns removed items

splice returns the removed elements, not the array.

Interview Questions

What is the main difference?

slice copies, splice mutates.

What does splice return?

An array of removed elements.

When should you use slice?

When you want immutability.

Practice Problem

Practice: Remove the middle element from an array using splice.

const nums = [1, 2, 3, 4, 5];
// TODO: remove 3

One Possible Solution

const nums = [1, 2, 3, 4, 5];
nums.splice(2, 1);
console.log(nums);

Frequently Asked Questions

Does slice mutate?

No, slice returns a new array.

Does splice mutate?

Yes, splice changes the original array.

Can splice insert and remove?

Yes, it can do both in one call.

Try It Yourself

Try editing the indexes to see how results change.