slice vs. splice in JavaScript
In JavaScript, we usually work with arrays and there is often a need to manipulate the array for extracting elements. Two commonly used methods for this purpose are slice() and splice(). While both may sound similar, they have different purposes, and understanding such differences is crucial for efficient array manipulation. In this article, we'll explore the differences between slice and splice in JavaScript.
Splice
- The splice() method is useful in adding or removing elements from an array. When the method is called, it modifies the original array by removing elements as specified by the deleteCount parameter and optionally adding new elements at the same position.
- An array of all the removed elements will be returned and an empty array is returned if no elements are removed.
Syntax:
Its syntax is as follows:
- array: The array on which the operation will be performed.
- start: The index at which the modification will begin.
- deleteCount: The number of elements to be removed from the array.
- item1, item2, ... (optional): Elements to be added at the specified index.
Example
Consider an array representing months of the year:
Now, let's say we want to replace the last three months with a new set of names. We can achieve this using the splice() method:
In this example, the start index(9) is at which the modification begins and the deleteCount(3) represents the number of elements to remove and the name of months('Oct', 'Nov', 'Dec') in the method are the elements to add in place of the removed months. The elements will be removed from the 9th index to the 11th index.
Here are some more examples of splice methods:
When deleteCount is set to 0, no elements are removed from the array and when it is omitted, or if its value exceeds the number of elements after the specified start index, the method removes all elements from the start index to the end of the array. If the item parameters are not provided, the method acts solely as a removal tool, deleting the specified number of elements without inserting new elements.
Explanation
- The splice(2) operation removes all elements from the array starting from the third index (March) to the end. The removedMonths array will contain the removed months.
- The splice(undefined, 2) operation removes the first two elements of the array (January and February). The removedMonths array will contain the deleted months.
- The splice(2, 0, 'Jan', 'Feb') operation adds 'Jan' and 'Feb' at the third index (March) without removing any existing elements. The removedMonths array is empty because no elements are deleted.
You can explore more about the splice method in this article.
Slice
- The slice() method is used for extracting a portion of an array, without modifying the original array.
- When the method is called, it creates a new array and copies the elements from the specified range of the original array into the new array.
- The original array remains unaltered. This method provides a non-destructive way to obtain a subset of elements, making it useful for various scenarios.
Syntax
Its syntax of the splice method is:
- array: The array from which elements will be extracted.
- start: The index at which the extraction begins.
- end (optional): The index at which the extraction ends. The element at the end index itself is not included in the sliced array. If the parameter is not provided, the method extracts all elements from the start till the end of the array.
Example
Consider an array representing months of the year:
Let us extract the first six months from the monthsOfYear array:
The code uses the slice() method to create a new array, firstHalf, by extracting elements starting from the 0th index up to the 6th, but not including, the element at index 6.
Now, let's say we want to create a new array containing the summer months of a year from June to August. We can use the slice() method for this purpose:
In this example, the start parameter(3) is the index of 'April' in the array, and the end parameter(8) is the index of 'August' in the array.
Here are some more examples of slice methods:
Explanation
- The slice() creates a shallow copy of the array, assigning it to a new variable (duplicate).
- The slice(1) creates a new array element from the second index of the original array. The slice(-2) extracts the last two elements of the original array.
- The slice(2, -1) creates a new array from the third index (March) to the second-to-last index of the original array.
You can explore more about the slice method in this article.
Difference between Array.slice() and Array.splice() in JavaScript
Criteria | Array.slice() | Array.splice() |
---|---|---|
Purpose | Extracts elements by creating a new array. | Executes adding, replacing or removing elements for modifying an array. |
Modifies Original Array | No, returns a new array. | Yes, directly modifies the original array. |
Parameters | The Start is the index at which the extraction will begin and the End (optional) is the index at which the extraction will end. | The start is the index at which the modification will begin and the DeleteCount is the number of elements to be removed from the array. The Items is an optional parameter representing elements to be added at the specified index. |
Return Value | Shallow copy of the selected array portion. | Array containing the removed elements. |
Example:
Consider a scenario in a weather application where historical temperature data is stored in an array representing months. When generating a monthly report, you may use Array.slice() to extract the required data without altering the original array.
In an e-commerce system, imagine managing a shopping cart represented as an array of items. When a customer adds or removes items, Array.splice() becomes valuable. It allows you to directly modify the original cart array by adding new items or removing those that are no longer desired.
Conclusion
- The Array.splice() method in JavaScript performs in-place modification of arrays, allowing developers to add, remove, or replace elements at specific indices within the original array. Its syntax includes parameters for the start index, delete count, and optional elements to be added.
- The Array.slice() method in JavaScript allows developers to create a new array by extracting a specified portion of an original array, providing a non-destructive method for obtaining subsets of data without altering the source array. The syntax has the start and optional end indices.
- Key differences include slice() returning a new array and being non-destructive, while splice() directly alters the original array and returns an array containing the removed elements. Understanding these distinctions is crucial for efficient array manipulation.