Problem Statement
Explain splice and slice methods. What is the difference and when would you use each?
Explanation
Splice and slice are commonly confused because of similar names, but they do very different things.
The splice method modifies the original array by adding, removing, or replacing elements. It takes start index, number of elements to delete, and optional elements to add. Returns an array of deleted elements. Use splice when you need to change the array in place.
The slice method creates a shallow copy of a portion of an array. It takes start and end indices. It does not modify the original array. Returns a new array. Use slice when you need a copy without changing the original.
Key differences:
Splice mutates the array, slice does not. Splice can add and remove, slice only copies. Splice returns deleted elements, slice returns new array.
Memory trick:
Splice has p for permanent change. Slice has no p, so no permanent change.
Common use cases:
Splice for removing items, inserting items, or replacing items. Slice for copying arrays, getting subarrays, or implementing pagination.
Code Solution
SolutionRead Only
// SPLICE - modifies original array const arr1 = [1, 2, 3, 4, 5]; // Remove elements const removed = arr1.splice(2, 2); // Start at index 2, remove 2 elements console.log(arr1); // [1, 2, 5] (modified!) console.log(removed); // [3, 4] (deleted elements) // Insert elements arr1.splice(2, 0, 'a', 'b'); // Start at 2, remove 0, add 'a' and 'b' console.log(arr1); // [1, 2, 'a', 'b', 5] // Replace elements arr1.splice(0, 2, 'x', 'y'); // Remove first 2, add 'x' and 'y' console.log(arr1); // ['x', 'y', 'a', 'b', 5] // Remove from end const last = arr1.splice(-1); // Remove last element console.log(last); // [5] // SLICE - does NOT modify original const arr2 = [1, 2, 3, 4, 5]; // Get portion const portion = arr2.slice(1, 4); // From index 1 to 4 (not including 4) console.log(portion); // [2, 3, 4] console.log(arr2); // [1, 2, 3, 4, 5] (unchanged!) // Copy entire array const copy = arr2.slice(); console.log(copy); // [1, 2, 3, 4, 5] // Get last n elements const lastTwo = arr2.slice(-2); console.log(lastTwo); // [4, 5] // Negative indices const middle = arr2.slice(1, -1); console.log(middle); // [2, 3, 4]
