JavaScript › Arrays & Array Methods

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

Intermediate

Answer

splice() mutates the original array by adding or removing elements in place and returns the removed elements; slice() returns a shallow copy of a portion of the array and leaves the original untouched.
const a = [1,2,3,4];
a.splice(1,2); // a is now [1,4]
const b = [1,2,3,4].slice(1,3); // [2,3], original unchanged
Real-world example splice() to remove a completed to-do item in place; slice() to grab a page of results for pagination.

Common follow-ups: Why is mutating arrays with splice() sometimes considered risky in React state?