Home >>JavaScript Array Reference >JavaScript Array splice() Method

JavaScript Array splice() Method

JavaScript Array splice() Method

JavaScript splice() method is used to add or remove items to/from the given input array and return the removed items. It changes the original given array.

Syntax:
array.splice(index, howmany, item1, ....., itemX)

Parameter Values

Parameter Description
index This is a required parameter. It defines an integer that specifies at what position to add/remove items.
howmany This is an optional parameter. It defines the number of items to be removed.
item1, ..., itemX This is an optional parameter. It defines the new items to be added to the array.

Browser Support

Method Chrome Edge Firefox Safari Opera
splice() Yes Yes Yes Yes Yess
Here is an example of JavaScript splice() method:
<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
var x = ["1", "2", "3", "4"];
document.getElementById("demo").innerHTML = x;
function myFunction() 
{
  x.splice(2, 0, "x", "x");
  document.getElementById("demo").innerHTML = x;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.

Example 2:
<html>
<body>
<p>Click the button to see the Output.</p>
<button onclick="myFunction1()">Try it</button>
<p id="demo1"></p>
<script>
var x = ["1", "2", "3", "4"];
document.getElementById("demo1").innerHTML = x;
function myFunction1() 
{
  x.splice(2, 1, "x", "x");
  document.getElementById("demo1").innerHTML = x;
}
</script>
</body>
</html>
Output:

Click the button to see the Output.


No Sidebar ads