splice()
The splice() function is used to alter the array. The alteration includes removing the elements, replacing the elements with some other elements, and adding new elements.
Syntax
array.splice(start, deleteCount, item1, item2, ...)
Parameters
start: The index at which to start modifying the array. If negative, it indicates an offset from the end of the array. For example, -1 refers to the last element. If start is greater than the length of the array, no elements will be removed or added.
deleteCount: The number of elements to remove from the array. If omitted or if greater than the number of elements from start to the end of the array, all elements from start to the end of the array will be removed.
item1, item2, ...: Optional. Elements to add to the array at the specified start index. If omitted, no elements will be added.
Return Type
The splice() method returns an array containing the deleted elements, if any. If no elements are deleted (i.e., deleteCount is 0), an empty array is returned. If no elements are removed or added, splice() returns an empty array regardless of the value of deleteCount. Importantly, the original array is modified in place.
Javascript Splice() Examples
Removing the elements
The splice function can be employed in the following way to remove the elements.
name_of_the_array.splice(start_index,no_of_elements) ;

You can also try this code with Online Javascript Compiler
Run Code
Here, start_index denotes the index from which the removal will start and no_of_elements is the number of the elements that will be removed.
Example 1
<script>
var example_1=[1,2,3,4,5,6,7];
example_1.splice(2,4);
console.log(example_1); //prints 1,2,7
</script>

You can also try this code with Online Javascript Compiler
Run Code
Here, 4 elements starting from index 2(elements value:3) are removed from the array.
Here also, the second argument is optional. In case, the second argument is not specified, automatically, all elements from the specified index are removed.
Example 2
<script>
var example_1=[1,2,3,4,5,6,7];
example_1.splice(2);
console.log(example_1); //prints 1,2
</script>

You can also try this code with Online Javascript Compiler
Run Code
Since there is only one argument, it is treated as the starting index from where element removal starts, and all the elements are removed after that are removed as no argument for that has been passed.
In case no argument is passed in the function, it does nothing. But also does not return any kind of error.
Replacing the elements
To replace the already existing elements in the array. The following code convection is used:
name_of_the_array.splice(starting_index,no_of_elements,replacing_element_1,replacing_element_2,replacing_element_3,...);

You can also try this code with Online Javascript Compiler
Run Code
Here, starting_indesx denotes the index from which replacing of the elements will start, no_of_elements represents the number of elements starting from the staring_index will be replaced. The replacing_elements are the elements that will replace the original elements.
This will become more clear with a few examples.
<script>
var example_1=[1,2,3,4,5,6,7];
example_1.splice(1,2,9);
console.log(example_1); //prints 1,9,4,5,6,7
</script>

You can also try this code with Online Javascript Compiler
Run Code
In the above example, 2 elements starting from index 1(elements value:2) have been replaced with element 9.
More than one element can also replace the original elements.
Example 3
<script>
var example_1=[1,2,3,4,5,6,7];
example_1.splice(1,2,9,10,11,12,13);
console.log(example_1); //prints 1,9,10,11,12,13,4,5,6,7
</script>

You can also try this code with Online Javascript Compiler
Run Code
Here, 9,10,11,12,13 replace [2,3] in the array ‘example_1’.
Adding new elements
This technique is the same as replacing the elements in the array.
We just specify the number of elements that are to be replaced with 0.
Example 4
<script>
var example_1=[1,2,3,4,5,6,7];
example_1.splice(1,0,9,10,11,12,13);
console.log(example_1); //prints 1,9,10,11,12,13,2,3,4,5,6,7
</script>

You can also try this code with Online Javascript Compiler
Run Code
Here, new elements have been put into the array, but none has been replaced.
Until now, you may have noticed that the slice() method creates a new array with the elements from the original array, whereas the splice() function reflects the changes in the original array.
Why Use Splice()?
The splice() method in JavaScript is widely used for its versatility in modifying arrays. Here are some reasons why splice() is commonly used:
- Inserting and Removing Elements: splice() allows you to remove elements from an array and optionally insert new elements at the same time. This makes it useful for tasks like adding or removing items from a list, managing dynamic content, or implementing features like drag-and-drop reordering.
- Dynamic Array Manipulation: With splice(), you can dynamically manipulate the contents of an array based on runtime conditions. This flexibility enables dynamic data structures and algorithms where the size and content of the array need to change dynamically.
- Efficient Array Modification: Unlike methods like shift() and unshift() which can be inefficient for large arrays due to shifting elements, splice() efficiently removes and inserts elements in place, minimizing the overhead associated with array modifications.
- Array Concatenation and Splitting: By using splice() in combination with other array methods, you can concatenate arrays, split arrays into multiple parts, or extract specific segments of an array, facilitating complex data transformations and processing.
- In-place Modification: The splice() method modifies the original array in place, avoiding the need to create new array objects. This can be beneficial for memory efficiency and performance, especially when working with large datasets.
Key Differences Between Slice() and Splice() in Javascript
The slice() and splice() methods in JavaScript are both used to manipulate arrays, but they have different purposes and behaviors. Here are the key differences between slice() and splice():
Purpose:
- slice(): The slice() method is used to extract a portion of an array and returns a new array containing the extracted elements.
- splice(): The splice() method is used to change the contents of an array by removing or replacing existing elements and/or adding new elements in place.
Modification of Original Array:
- slice(): The slice() method does not modify the original array; it returns a new array with the extracted elements.
- splice(): The splice() method modifies the original array in place by removing or replacing elements and optionally adding new elements.
Return Value:
- slice(): The slice() method returns a new array containing the extracted elements.
- splice(): The splice() method returns an array containing the deleted elements, if any. If no elements are deleted, an empty array is returned.
Parameters:
- slice(): The slice() method takes two parameters: start and end, specifying the start and end indices for extraction. It extracts elements from start up to, but not including, end.
- splice(): The splice() method takes multiple parameters: start, deleteCount, and optional items to add. start specifies the index at which to start modifying the array, deleteCount specifies the number of elements to remove, and optional items are added at the specified index.
Usage:
- slice(): slice() is commonly used for creating shallow copies of arrays, extracting subarrays, and immutable array operations.
- splice(): splice() is commonly used for dynamic array manipulation, inserting or removing elements from arrays, and in-place array modifications.
Use cases
Now, we are aware that the slice() method keeps the original array intact. So, when there is a situation where we need to form a new array with few elements from the already existing array, we can use splice() in that scenario.
In cases where we need to make changes in the already existing array, and we may not need the original array in the future, we use splice(). Although, the features that this method offers are of great variety compared with the slice() method.
Frequently Asked Questions
Does the slice() method bring any change in the original array in JavaScript?
No, the slice() method does not change the array.
Is it necessary to store the return array by JavaScript's splice() method?
No, it is not compulsory to store the array returned by JavaScript's splice() method.
What functionality does the splice() method provide in JavaScript?
The splice() method allows deleting elements, replacing elements, and adding new elements to the array in JavaScript.
Is JavaScript slice () a deep copy?
Yes, JavaScript slice() method creates a shallow copy of an array, meaning it copies references to the original array's elements.
Is slice immutable vs splice?
slice() is immutable, returning a new array without modifying the original, while splice() modifies the original array in place.
Conclusion
This article extensively discusses a few differences between the slice() and splice() methods in JavaScript. We have also included example code to make the concepts more clear.
Check out the following problems -
We hope that this blog has helped you enhance your knowledge regarding the differentiation between Array Slice and Splice Methods and if you would like to learn more, check out our articles on JavaScript. Do upvote our blog to help other ninjas grow.
Happy Coding!