23 Feb 2024
In JavaScript, slice and splice are two different array methods that are used for manipulating arrays, but they serve different purposes.
-
slice(): This method returns a shallow copy of a portion of an array into a new array object selected frombegintoend(endnot included). The original array will not be modified.Syntax:
array.slice(begin, end)begin: The beginning index (inclusive) where extraction starts. If negative, it is treated asarray.length + begin.end: The end index (exclusive) where extraction ends. If omitted, slice extracts through the end of the sequence. If negative, it is treated asarray.length + end.
Example:
const array = [1, 2, 3, 4, 5]; const slicedArray = array.slice(1, 3); console.log(slicedArray); // Output: [2, 3] console.log(array); // Output: [1, 2, 3, 4, 5] (original array remains unchanged) -
splice(): This method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. It modifies the original array.Syntax:
array.splice(start, deleteCount, item1, item2, ...)start: The index at which to start changing the array.deleteCount: The number of elements in the array to remove fromstart.item1, item2, ...: The elements to add to the array, beginning fromstart.
Example:
const array = [1, 2, 3, 4, 5]; const removedElements = array.splice(1, 2); // Removes 2 elements starting from index 1 console.log(removedElements); // Output: [2, 3] console.log(array); // Output: [1, 4, 5] (original array modified)
Summary: slice is used to create a new array by extracting a portion of an existing array without modifying it, while splice is used to modify the original array by adding, removing, or replacing elements at a specified index.