JavaScript Interview Question #40

What is the difference between slice() and splice()?

Objects, Arrays & Core Data Handling Junior Beginner

Quick Interview Answer

slice returns a shallow copy of a selected portion of an array without modifying the original. splice changes the original array by removing, replacing, or inserting elements.

Detailed Explanation

slice returns a shallow copy of a selected portion of an array without modifying the original. splice changes the original array by removing, replacing, or inserting elements.

This mutation difference is a common interview question. slice is frequently used when non-mutating behavior is desired, while splice is appropriate when intentional in-place modification is required.

Code Example

const numbers = [1, 2, 3, 4, 5];

const part = numbers.slice(1, 4);
console.log(part);    // [2, 3, 4]
console.log(numbers); // unchanged

numbers.splice(1, 2, 20, 30);
console.log(numbers); // [1, 20, 30, 4, 5]