slice vs splice in JavaScript
Easy to confuse by name, but they behave very differently — one is safe, one mutates.
The difference
slice(start, end) returns a COPY of a portion without changing the original — non-mutating. splice(start, deleteCount, ...items) MUTATES the array in place (removing/inserting) and returns the removed elements.
const a = [1, 2, 3, 4];
a.slice(1, 3); // [2, 3] — a unchanged
a.splice(1, 2); // [2, 3] — a is now [1, 4]Why it matters in React
State must not be mutated. Use slice (and spread) to produce new arrays; avoid splice on state. Remembering 'splice mutates' prevents a common re-render bug.
Master arrays and mutation
Mutating vs non-mutating methods and the array questions interviewers ask — in the JavaScript Interview Kit.
⚡ Get the JavaScript Interview Kit → ₹299Frequently asked questions
- How do I remember which mutates?
- splice has an extra letter and does extra work — it mutates. slice is the clean, non-mutating copy.
- Which is safe for React state?
- slice (non-mutating). splice mutates in place, which can cause missed re-renders.
