Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
slice() 
2.1.
Syntax
2.2.
Parameter
2.3.
Return Type
2.4.
Javascript slice() example
2.5.
Why Use Slice()?
3.
splice()
3.1.
Syntax
3.2.
Parameters
3.3.
Return Type
3.4.
Javascript Splice() Examples
3.5.
Why Use Splice()?
4.
Key Differences Between Slice() and Splice() in Javascript
5.
Use cases
6.
Frequently Asked Questions
6.1.
Does the slice() method bring any change in the original array in JavaScript? 
6.2.
Is it necessary to store the return array by JavaScript's splice() method?
6.3.
What functionality does the splice() method provide in JavaScript? 
6.4.
Is JavaScript slice () a deep copy?
6.5.
Is slice immutable vs splice?
7.
Conclusion
Last Updated: May 15, 2024
Easy

Differentiate between Array Slice and Splice Javascript

Author Vidhi Singh
0 upvote
Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

We have a data structure called an array, which makes it easier for us to store the related entities together. Even though the elements of an array share some similar characteristics, sometimes we may need some out of them only. We need some techniques to provide us with those elements in those situations. 

Differentiate between Array Slice and Splice Javascript

We have two arrays methods supporting this functionality in Javascript: slice () and splice(). 
Since they sound very similar, one might get confused if they have identical characteristics. But that’s not true. They are very different from each other and provide completely different functionality. 

This article will discuss the two arrays methods in JavaScript, namely, slice() and splice(). 

slice() 

In JavaScript, the slice() function is used to get a sub-array from the array. It takes two arguments, and the arguments that this function takes are - the starting index and the ending index of the array of which we want to create the sub-array.  
For example, the array is [1,2,3,4,5,6,7,8], and we want the sub-array [3,4,5]. So, the starting index will be 2, and the ending index will be 4. Of course, it is 0 based indexing as it is an array.

Syntax

Let’s see the syntax for the same: 

name_ of_array.slice(starting_index,ending_index);  

Parameter

starting_index: The index at which to begin extraction. This parameter is optional. If omitted, the slice starts from index 0. If negative, it indicates an offset from the end of the array. For example, -1 refers to the last element.

ending_index: The index before which to end extraction. The slice() method extracts up to, but does not include, the element at the ending index. This parameter is also optional. If omitted, the slice extends to the end of the array. If negative, it indicates an offset from the end of the array.

Return Type

The slice() method, in JavaScript, returns the sub-array as a new array. That’s why we directly printed it on the console. 

For example, 

<script> 
var example_1=[1,2,3,4,5,6,7];
console.log(example_1.slice(2,5));    //prints 3,4,5,6 
</script> 

 

Here, we can also store the result in a variable, if required.

Javascript slice() example

Example 1

<script> 
	var example_1=[1,2,3,4,5,6];
	console.log(example_1.slice(2,4));    //prints 3,4,5 
</script> 

 

In case, only one argument is passed to the function, it is considered the starting index. The end index, in this case, is automatically assumed as the last index. Because of which the second argument is optional.

Example 2

<script> 
	var example_1=[1,2,3,4,5,6,7,8];
	console.log(example_1.slice(2));    //prints 3,4,5,6,7,8
</script> 

 

Also, if no argument is passed at all, then the whole array is returned. 

For instance,

<script> 
	var example_1=[1,2,3,4,5,6,7];
	console.log(example_1.slice());    //prints 1,2,3,4,5,6,7
</script>  

 

Negative indices are also accepted by the slice() function. It works similar to what negative indices do in arrays. 

Example 3

<script> 
	var example_1=[1,2,3,4,5,6,7];
	console.log(example_1.slice(-2,2));    //prints 6,7,1,2,3 
</script>

Why Use Slice()?

The slice() method in JavaScript is commonly used for extracting a portion of an array into a new array without modifying the original array. Here are some reasons why slice() is useful:

  • Non-destructive Operation: Unlike other array methods like splice() that modify the original array, slice() performs a non-destructive operation. It creates a new array containing the extracted elements, leaving the original array unchanged. This is particularly useful when you need to preserve the original array while working with a subset of its elements.
  • Creating Subarrays: slice() allows you to easily create subarrays by extracting a range of elements from the original array. This is helpful for tasks such as pagination, where you may need to display a subset of data at a time.
  • Flexible Extraction: With slice(), you can specify the starting and ending indices to precisely define the portion of the array you want to extract. This flexibility allows you to extract elements from any position in the array, making it suitable for various data manipulation tasks.
  • Method Chaining: Since slice() returns a new array, it can be easily chained with other array methods like map(), filter(), and reduce() to perform complex data transformations. This enables concise and expressive code that enhances readability and maintainability.
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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) ;

 

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> 


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>

 

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,...);

 

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> 

 

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> 

 

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> 

 

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!    

Previous article
Convert Snake Case String to Camel Case String
Next article
Difference between Javascript Push and Concat methods
Live masterclass