What is the difference between slice and splice?
They look almost identical but do completely different things. Slice returns a new array containing a portion of the original and leaves the original untouched. Splice changes the original array by removing, replacing or inserting elements in place, and it returns the elements it removed.
const letters = ["a", "b", "c", "d"];
// slice returns a new array and leaves the original alone.
const part = letters.slice(1, 3);
console.log(part); // ["b", "c"]
console.log(letters); // ["a", "b", "c", "d"]
console.log(letters.slice(-2)); // ["c", "d"]
// splice mutates the original array.
const removed = letters.splice(1, 2, "X");
console.log(removed); // ["b", "c"]
console.log(letters); // ["a", "X", "d"]The slice indexes are a start position and an end position, and the end is exclusive. Negative numbers count from the end, so a slice of minus two gives you the last two elements. Omitting the end means the end of the array.
Splice takes a start position, a count of elements to remove, and then any number of items to insert at that position. It returns the removed elements as a new array, and it modifies the array it was called on. Calling splice with only a start position removes everything from that position onwards, which is a common way to truncate an array in place.
The name confusion is the only real hazard, and it has caught everyone. If you remember that slice gives you a slice back and splice splices things out, you will not get it wrong twice.