splice() Function is used to add or remove elements from an Array.
Let us say, we have a Array that contains four names, Mohan, Kriti, Philip and Salim. And we want to remove the elements Kriti and Philip from the Array.
<html> <body> <script> var x = ["Mohan", "Kriti", "Philip", "Salim"] x.splice(1,2) document.write(x) </script> </body> </html>
So, we have the below Array,
var x = ["Mohan", "Kriti", "Philip", "Salim"]
And we want to remove the elements Kriti and Philip from the Array.
x.splice(1,2)
Next, let us say, we have a Array that contains four names, Mohan, Kriti, Philip and Salim. And we want to add the name Benny in between Philip and Salim.
<html> <body> <script> var x = ["Mohan", "Kriti", "Philip", "Salim"] x.splice(3, 0, "Benny") document.write(x) </script> </body> </html>
So, all we have done is used the splice() method to add the name Benny at index 3. And also mentioned 0. So that no elements gets removed from the array.
x.splice(3, 0, "Benny")
And what happens is Benny gets inserted at index 3 pushing Salim at index 4.