Junior — Middle
Can you explain the difference between the slice and splice methods when working with arrays in JavaScript?
sobes.tech AI
Answer from AI
The methods slice and splice in JavaScript work with arrays but have different purposes:
-
slice(start, end)— returns a new array containing a copy of a portion of the original array from indexstarttoend(excludingend). The original array remains unchanged. -
splice(start, deleteCount, ...items)— modifies the original array by removingdeleteCountelements starting from indexstart, and insertsitemsin their place (if specified). It returns an array of the removed elements.
Example:
let arr = [1, 2, 3, 4, 5];
// slice
let newArr = arr.slice(1, 3); // [2, 3]
console.log(arr); // [1, 2, 3, 4, 5] - the original array is unchanged
// splice
let removed = arr.splice(1, 2, 8, 9); // removes 2 elements from index 1 and inserts 8, 9
console.log(arr); // [1, 8, 9, 4, 5]
console.log(removed); // [2, 3]
Thus, slice is for creating a subarray without modifying the original, while splice is for modifying the array in place.