JavaScript · The language round
What is the difference between slice and splice?
Short answer
slice returns a shallow copy of a section without changing the original array. splice mutates the original array and returns the removed elements.
The names are similar, but the mutation behaviour is opposite. This is a common interview question because it tests whether you know which array methods are pure.
const letters = ["a", "b", "c", "d"];
const slice = letters.slice(1, 3);
console.log(slice); // ["b", "c"]
console.log(letters); // ["a", "b", "c", "d"]
const removed = letters.splice(1, 2, "x");
console.log(removed); // ["b", "c"]
console.log(letters); // ["a", "x", "d"]Arguments and return values
slice(start, end)copies fromstartup to but not includingendsplice(start, deleteCount, ...items)removes elements and inserts new ones- Negative indexes count from the end for both methods
slicereturns a new array;splicereturns the removed elements
The copy from slice is shallow. Objects inside the new array are still the same references as the objects in the original array.
const original = [{ id: 1 }];
const copy = original.slice();
copy[0].id = 99;
console.log(original[0].id); // 99toSorted, toReversed and toSpliced. They return new arrays and leave the source untouched.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1Which method mutates the original array?
- 2How do negative indexes work in `slice`?
- 3Is the array returned by `slice` a deep copy?
- 4How would you remove an item without mutating the array?
Say it in the interview
slice copies a section of an array and returns a new array without changing the original. splice mutates the original by removing or inserting elements and returns the removed elements. Both support negative indexes. The copy from slice is shallow, so nested objects are shared. When I need immutability I use slice or the newer toSpliced method.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live JavaScript mock interview and get scored feedback on depth, clarity and confidence.