Table of contents
1.
Introduction
2.
What is JavaScript Array splice()?
3.
Syntax of Javascript splice()
3.1.
Javascript
4.
Parameters of Javascript splice()
4.1.
startIndex 
4.2.
remove_count
4.3.
items_list
5.
Return Value of Javascript splice()
6.
Examples of the Javascript Splice() Method
6.1.
Using Splice() to Remove and Insert Elements
6.2.
Javascript
6.3.
Javascript
6.4.
Javascript
6.5.
Javascript
6.6.
Javascript
6.7.
Using Splice() on a Sparse Array
6.8.
Javascript
7.
How to Use JavaScript Array Splice?
7.1.
Javascript
7.2.
Javascript
8.
Advantages of the Javascript Splice Method
9.
Disadvantages of the Javascript Splice Method
10.
Frequently Asked Questions
10.1.
What is splice in JavaScript?
10.2.
Is splice () and slice () same in JavaScript?
10.3.
What is array splice (-1,1) in JavaScript?
10.4.
What is the difference between splice and shift in JavaScript? 
10.5.
What is the return value of the splice() method?
11.
Conclusion
Last Updated: Jun 18, 2024
Easy

JavaScript Array splice() Method

Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

Javascript is a dynamic and versatile programming language widely used in web development. One of its powerful built-in methods is the array splice() method. This method is very useful for developers, allowing them to modify arrays in many different ways, such as adding, removing, or replacing elements. The splice() method is flexible and efficient and provides useful features, such as returning the removed elements.

javascript splice

For any developer who works with arrays in Javascript, the splice() method is an essential tool to master. So fasten your seat belt, and let’s start to learn the Javascript splice() method!

What is JavaScript Array splice()?

The splice() method modifies an array's items by deleting or replacing them and/or inserting new ones in their place. It is done to gain access to a portion of an Array without changing its value.

The splice() method in JavaScript is operated to add or remove elements from an array and returns the extracted items. It alters the original array and can also add new elements at any position within the array.

Syntax of Javascript splice()

Following is the syntax of the javascript splice method.

  • Javascript

Javascript

splice(startIndex, remove_count, item1, item2,..., itemN)
You can also try this code with Online Javascript Compiler
Run Code

Parameters of Javascript splice()

The parameter used in the syntax of the javascript splice method is:

startIndex 

  • It is a necessary parameter.
     
  • It is the index from where we are requesting the changes to happen.
     
  • If startIndex < 0, start + array.length is utilized.
     
  • If startIndex < -array.length or start is not specified, start’s value is used as 0.
     
  • If startIndex >= array.length, no element is removed, but the procedure acts as an adding function, adding as many elements as specified.

remove_count

  • It is an optional parameter.
     
  • It indicates the number of elements to be removed.
     
  • All of the elements of the array will be deleted if remove_count is larger than the number of elements present in the array.

items_list

  • It is an optional parameter.
     
  • These elements are going to be added at the start index.
     
  • If no elements are specified, then the splice() will use startIndex and remove_count to identify the specified number of elements and the specified index. It will then simply remove the specified number of elements from the array starting from the specified index.

Return Value of Javascript splice()

  • An array containing the elements that have been removed.
     
  • If only one element is removed, a one-element array is returned.
     
  • If no elements are removed, the array is returned empty.

Examples of the Javascript Splice() Method

Following are some examples of usage of the javascript splice() method.

Using Splice() to Remove and Insert Elements

1. Removing 0 elements before an index and inserting other elements.

In this example, we are removing 0 elements and inserting an element at the 2nd position.

Code:

  • Javascript

Javascript

const myDogs = ["pug", "husky", "poodle", "bulldog", "hound"]
const removed = myDogs.splice(2, 0, "labrador");
console.log(removed);
console.log(myDogs);
You can also try this code with Online Javascript Compiler
Run Code


Output:

[]
['pug', 'husky', 'labrador', 'poodle', 'bulldog', 'hound']

 

2. Removing an element and inserting other elements.

After learning how to insert an element. Let’s see how to simultaneously remove and insert elements using javascript splice methods.

Code:

  • Javascript

Javascript

const myDogs = ["pug", "husky", "poodle", "bulldog", "hound"];
const removed = myDogs.splice(2, 1, "labrador");
console.log(removed);
console.log(myDogs);
You can also try this code with Online Javascript Compiler
Run Code


Output:

['poodle']
['pug', 'husky', 'labrador', 'bulldog', 'hound']

 

3. Removing two elements from an index.

Let’s take an example of removing two elements from index 2.

Code:

  • Javascript

Javascript

const myDogs = ["pug", "husky", "poodle", "bulldog", "hound"];
const removed = myDogs.splice(2, 2);
console.log(removed);
console.log(myDogs);
You can also try this code with Online Javascript Compiler
Run Code


Output:

['poodle', 'bulldog']
['pug', 'husky', 'hound']

 

4. Removing an element from the index -k.

We will now take an example of removing an element from the index -2. 

Code:

  • Javascript

Javascript

const myDogs = ["pug", "husky", "poodle", "hound"];
const removed = myDogs.splice(-2, 1);
console.log(removed);
console.log(myDogs);
You can also try this code with Online Javascript Compiler
Run Code


Output:

['poodle']
['pug', 'husky', 'hound']

 

Since the index is negativeindex + arr.length is used as the index. Thus the new_index is 2. So poodle is removed.

 

5. Removing all elements starting from an index.

Now, let’s see how to use the javascript splice method to remove all elements starting from index 2.

Code:

  • Javascript

Javascript

const myDogs = ["pug", "husky", "poodle", "hound"];
const removed = myDogs.splice(2);
console.log(removed);
console.log(myDogs);
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

['poodle', 'hound']
['pug', 'husky']

Using Splice() on a Sparse Array

The javascript splice() method can also be used to preserve the array's sparseness. In JavaScript, the splice() method can be used to modify a sparse array by adding, removing, or replacing elements. The method preserves the sparseness of the array by not filling empty elements with undefined when removing elements, and not creating dense arrays when inserting elements.

Code:

  • Javascript

Javascript

const sparray = [10, , 30, 40, , 60];
console.log(sparray.splice(1, 2)); 
console.log(sparray); 
You can also try this code with Online Javascript Compiler
Run Code

 

Output:

[< empty item>, 30]
[10, 40, < empty item>, 60]

 

The code initializes a sparse array sparray. splice() is then used to remove two elements starting from index 1, preserving the sparseness of the array. The removed elements [undefined, 30] are logged first, and the updated sparray is logged next.

How to Use JavaScript Array Splice?

JavaScript's splice() modifies an array by adding, removing, or replacing elements. You can use it by providing two inputs to it. the first input indicates the array's starting index you want to change, and the second input shows the number of elements to remove from the start. 

  • Javascript

Javascript

const nums = [1, 2, 3, 4, 5];
nums.splice(2, 2);
//This removes the second element from nums
// result : nums = [1,2,5];
You can also try this code with Online Javascript Compiler
Run Code


You can also add new elements after the removal point. For example,

  • Javascript

Javascript

const nums = [1, 2, 3, 4, 5];
nums.splice(2, 3, 'a', 'b')
//This removes three elements starting from index 2 and inserts 'a' and 'b' in their place.
// result : nums = [1,2,'a','b',5];
You can also try this code with Online Javascript Compiler
Run Code

Omitting the second parameter removes elements from the specified index to the end of the array. splice() alters the original array, so be cautious.

Advantages of the Javascript Splice Method

The following are the advantages of using the Javascript splice() method.

  • Javascript splice() methods allow us to modify the array by inserting or removing elements in the array.
     
  • We can add or remove any elements at any place. Thus providing us with the flexibility to modify any part of the array.
     
  • Javascript splice() methods allow us to remove multiple elements at once.
     
  • The Javascript splice() method also provides us with a way to return the array of removed elements.

Disadvantages of the Javascript Splice Method

The following are the disadvantages of using the Javascript splice() method.

  • The Javascript splice() method can be complex to use, especially when you need to add or remove multiple elements at different positions in the array.
     
  • The Javascript splice() method modifies the original array, which can cause unexpected behaviour if you are not careful.
     
  • The Javascript splice() method can be slow for large arrays, especially if you need to remove or add a large number of elements.
     
  • The Javascript splice() method only work on array indices that are numeric. If your array has non-numeric keys, you may need to use other methods to modify it.

Frequently Asked Questions

What is splice in JavaScript?

The splice() method alters an array by removing or replacing existing elements and inserting new ones. The splice() method requires two arguments: the starting index to change the array from and the number of elements to eliminate. Extra parameters can also be specified to indicate which items should be added in place of the removed parts.

Is splice () and slice () same in JavaScript?

JavaScript has two distinct functions, namely 'splice()' and 'slice()', each serving different purposes. The 'splice()' function alters an array by adding, removing, or replacing elements. On the contrary, the 'slice()' function generates a fresh array comprising a copied section of an existing array.

What is array splice (-1,1) in JavaScript?

When using the splice() method in JavaScript, you can use negative starting index values to count entries from the end of the array rather than the beginning. By passing a negative number as the start parameter to splice(), you provide an index relative to the array's end. For example, -1 denotes the final element and so on.

What is the difference between splice and shift in JavaScript? 

"Splice" adds or removes elements from an array at a specified index. It can both remove elements and insert new ones in their place. On the other hand, "shift" is used to remove the first element from an array and shift all remaining elements to lower indices. It permanently removes the first element and updates the array length accordingly.

What is the return value of the splice() method?

The splice() method returns an array containing the removed elements. If no elements are removed, the method returns an empty array. The returned array may contain one or more elements, depending on the number of elements removed by the splice() method.

Conclusion

This article briefly discussed the javascript splice() method. We saw its syntax, parameter and various examples. We also discussed the advantages and disadvantages of the javascript splice() methods.

We hope this article has helped you understand the javascript splice() methods and all about it. 

Recommended Articles -

If you wish to test your competency in coding, check out the mock test series and take part in the contests hosted on Coding Ninjas Studio!

Happy Learning!

Live masterclass