Splice Method in JavaScript
Learn the usage of the splice method in javascript. The splice() method is one of the array methods in JS, which we can use only for arrays.
Array
It is a collection of data elements or data values. Arrays are created to store multiple values in a single variable.
Creating an Array
To create an array, we need to create a variable using the “var” keyword then we need to initialize the list of string or integer values between the square bracket. You must enclose the string value in the array in double-quotes. Since you are storing string values in an array, you should not store integer values in it. See the above syntax and examples of an array.
Syntax:
var array = [comma separated list of values];
Ex:
var studNames =["John", "Ravi", "Ram", "Raj"];
Splice() Method
- It changes the contents of an array by removing existing elements.
- And or adding new elements to the array.
- It returns a list of removed elements
Syntax:
splice(startindex:number, deleteCount:number, [ ...args])):Array
Where:
- start index: indicates the index of the element where insertion or deletion begins
- deleteCount: indicates the number of elements to be deleted
- …args: indicates list of elements to be inserted
- Array: indicates list of elements removed.
Example:
var studNames =["John", "Ravi", "Ram", "Raj"];
document.write(studNames.splice(2,1)); //Ram
document.write(studNames); John, Ravi, Raj
When the first line of executed, it goes to “studName” array 2 index and removes 1 element. So, here it remove “Ram” and returns “ram”.
document.write(studNames.splice(2,0, "Hitesh"));
document.write(studNames); // John, Ravi, Hitesh, Raj
- To add the value in array, we need to tell in splice() method, at which index you want to insert the value, how many values to remove and the value you want to add.
- Here, I want to add the value at index 2, 0 removes, adding value “Hitesh”.
Then our value is successfully added.