JavaScript Array splice() method is used to add, remove, or replace elements from an array. This method modifies the original array.
Syntax
array.splice(index, howmany, item1, ....., itemX)
Parameters
- index(required): The position at which to start modifying(add/remove) the array.
- howmany(optional): The number of elements to remove from the array. If you pass 0, that means no elements will be removed.
- item(optional): The elements to add to the array, starting from the specified index.
Return Value
Returns an array containing the deleted elements.
Visual Representation
The above figure shows that Model x which is in the first position will be removed after applying the slice() function.
Example 1: Basic Usage
let tesla = ['Model S', 'Model X', 'Model 3'];
let removedItem = tesla.splice(1, 1);
console.log('Remaining array:', tesla);
console.log('removedItem is:', removedItem);
Output
Remaining array: [ 'Model S', 'Model 3' ]
removedItem is: [ 'Model X' ]
Example 2: Replace an element
The above figure shows that we have replaced Model X which is in 1st position with Roadster.
let tesla = ['Model S', 'Model X', 'Model 3'];
let removedItem = tesla.splice(1, 1, 'Roadster');
console.log('Updated array:', tesla);
Output
Updated array: [ 'Model S', 'Roadster', 'Model 3' ]
Example 3: Add an element
The above figure shows that we have added Model Y to the 1st index.
let tesla = ['Model S', 'Model X', 'Model 3'];
tesla.splice(1, 0, "Model Y");
console.log('Array after adding element :', tesla);
Output
Array after adding element : [ 'Model S', 'Model Y', 'Model X', 'Model 3' ]
Example 4: Pass the start index negative(-)
let tesla = ['Model S', 'Model X', 'Model 3'];
let removedItem = tesla.splice(-1);
console.log(tesla);
console.log(removedItem);
Output
[ 'Model S', 'Model X' ]
[ 'Model 3' ]
Array splice() vs Array slice()
The splice() method modifies the original array and it can add, remove, or replace elements, while the slice() method returns a new array and doesn’t modify the original array.
Browser Compatibility
- Google Chrome 1
- Microsoft Edge 12
- Firefox 1
- Safari 1
- Opera 4
See also
Javascript array lastIndexOf()
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.