Using the JavaScript splice() method you can add and/or remove array elements. This method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.
array.splice(start, deleteCount, item1, ..., itemN)
It returns an array by changing (adding/removing) its elements in place.
index – The position to add/remove items.
deleteCount – Number of items to be removed. (Optional)
item – New elements(s) to be added. (Optional)
JavaScript splice() method
Simple example code adding, replacing, and removing elements of an array in JavaScript.
<!DOCTYPE html>
<html>
<body>
<script>
const months = ['Jan', 'March', 'April', 'June'];
// inserts at index 1
months.splice(1, 0, 'Feb');
console.log(months);
// replaces 1 element at index 4
months.splice(4, 1, 'May');
console.log(months)
// removing 3 elements
months.splice(2, 3);
console.log(months)
</script>
</body>
</html>
Output:
To access part of an array without modifying it, see slice()
.
Keep in mind that the splice()
method modifies the original array in place, so be cautious when using it, especially in scenarios where you need to keep the original array intact.
Comment if you have any doubts or suggestions on this JS basic method topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version