QA
Beginner LevelJavaScript & TypeScript

What is the difference between Array.prototype.slice() and Array.prototype.splice()?

❓ Interview Prompt: Compare slice (pure shallow copy) and splice (mutable inline deletion/insertion).

Despite their similar names, slice() and splice() have opposite mutability rules:

slice(start, end):

•
Pure (Immutable): Does NOT modify the original array.
•
Returns a new array containing a shallow copy of elements from start index up to (but not including) end index.

splice(start, deleteCount, item1, item2, ...):

•
Impure (Mutating): Modifies the original array directly.
•
Deletes deleteCount items starting at start index and optionally inserts new items in their place.
•
Returns an array containing the deleted elements.

Code Implementation Example

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

// 1. slice() does NOT mutate original array
const sliced = letters.slice(1, 4);
console.log(sliced);  // ['b', 'c', 'd']
console.log(letters); // ['a', 'b', 'c', 'd', 'e'] (Unchanged)

// 2. splice() MUTATES original array
const removed = letters.splice(2, 2, 'X', 'Y');
console.log(removed); // ['c', 'd'] (Deleted elements)
console.log(letters); // ['a', 'b', 'X', 'Y', 'e'] (Mutated!)
💡Pure slice non-mutating copy vs splice inline array modification.
🎯 Interview Key Takeaway

slice() is immutable and returns a shallow copy section; splice() mutates the array by deleting or inserting items.

#Arrays#Mutability#Methods#Beginner
Back to all JavaScript & TypeScript Questions→

More JavaScript & TypeScript Interview Questions

Beginner LevelJavaScript & TypeScript

What are the differences between var, let, and const in JavaScript?

Beginner LevelJavaScript & TypeScript

What are the JavaScript data types and the difference between primitives and objects?

Beginner LevelJavaScript & TypeScript

What is the difference between == (loose equality) and === (strict equality)?