Computer >> Computer tutorials >  >> Programming >> Javascript

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

<!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

JavaScript Array.splice() Method

Click the “Result” button above −

JavaScript Array.splice() Method

Example

<!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

JavaScript Array.splice() Method

Click the “Result” button −

JavaScript Array.splice() Method