What's the difference between splice() and slice()?
Short 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.
Advertisement
AModel 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 unchangedReal-world example
splice() to remove a completed to-do item in place; slice() to grab a page of results for pagination.
Likely follow-ups
- Why is mutating arrays with splice() sometimes considered risky in React state?
Related topics