JavaScript Array.splice() Method


The splice() method of JavaScript is used to add or remove item. It returns the removed item.

The syntax is as follows −

array.splice(index, num, item1, ....., itemX)

Here, index is the integer specifying at what position to add or remove items, num is the number of items to remove, item1…itemX are the items to be added to the array.

Let us now implement the splice() method in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<h2>Products</h2>
<p>Click to display the updated product list...</p>
<button onclick="display()">Result</button>
<p id="test"></p>
<script>
   var products = ["Electronics", "Books", "Accessories"];
   document.getElementById("test").innerHTML = products;
   function display() {
      products.splice(1, 2, "Pet Supplies", "Footwear");
      document.getElementById("test").innerHTML = products;
   }
</script>
</body>
</html>

Output

Click the “Result” button above −

Example

 Live Demo

<!DOCTYPE html>
<html>
<body>
<h2>Products</h2>
<p>Click to display the updated product list...</p>
<button onclick="display()">Result</button>
<p id="test"></p>
<script>
   var products = ["Electronics", "Books", "Accessories"];
   document.getElementById("test").innerHTML = products;
   function display() {
      products.splice(3, 1, "Pet Supplies", "Footwear", "Home Appliances");
      document.getElementById("test").innerHTML = products;
   }
</script>
</body>
</html>

Output

Click the “Result” button −

Updated on: 17-Dec-2019

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements