DEV Community

Cover image for JavaScript slice() vs splice() — Don't Mix Them Up 🚀
Shyamalendu Nayak
Shyamalendu Nayak

Posted on

JavaScript slice() vs splice() — Don't Mix Them Up 🚀

One of the most common JavaScript interview questions is:

What's the difference between slice() and splice()?

They sound almost identical, but they behave very differently.

🔹 slice()

slice() is used to extract a portion of an array without modifying the original array.

const arr = [10, 20, 30, 40, 50];

const result = arr.slice(1, 4);

console.log(result);
// [20, 30, 40]

console.log(arr);
// [10, 20, 30, 40, 50]
Enter fullscreen mode Exit fullscreen mode

Syntax:

array.slice(start, end)
Enter fullscreen mode Exit fullscreen mode

👉 The end index is not included.

Think of slice() as:

"Give me a copy of this portion."

🔹 splice()

splice() is used to add, remove, or replace elements in an array.

It modifies the original array.

// Remove elements
const arr = [10, 20, 30, 40, 50];

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

console.log(removed);
// [20, 30]

console.log(arr);
// [10, 40, 50]
Enter fullscreen mode Exit fullscreen mode

Syntax:

array.splice(start, deleteCount, ...items)
// Add elements
const arr = [10, 20, 40, 50];

arr.splice(2, 0, 30);

console.log(arr);
// [10, 20, 30, 40, 50]
// Replace elements
const arr = [10, 20, 30, 40];

arr.splice(1, 2, 200, 300);

console.log(arr);
// [10, 200, 300, 40]
Enter fullscreen mode Exit fullscreen mode

⚡ Quick Comparison
Feature slice() splice()
Modifies original array? ❌ No ✅ Yes
Extract elements? ✅ Yes ✅ Can remove
Add elements? ❌ No ✅ Yes
Replace elements? ❌ No ✅ Yes
Returns New array Removed elements
Syntax slice(start, end) splice(start, deleteCount, items)
🧠 Easy Way to Remember
slice() → Copy

const result = arr.slice(1, 3);

// Original array remains unchanged.

`splice()`  Change
arr.splice(1, 2);
Enter fullscreen mode Exit fullscreen mode

Original array gets modified.

🎯 Interview Answer

If an interviewer asks:

"What's the difference between slice and splice?"

You can answer:

"slice() returns a shallow copy of a portion of an array without modifying the original array. splice() modifies the original array and can be used to add, remove, or replace elements."

That's the key difference you need to remember.

slice = doesn't mutate 🧊
splice = mutates 🔥

Top comments (0)