How to use the splice() method in JavaScript?

The splice() method in JavaScript is used to add or remove elements from an array. The basic syntax is as follows:

array.splice(startIndex, numberOfElementsToRemove, elementsToAdd)
  • startIndex: The index at which to start changing the array.
  • numberOfElementsToRemove: The number of elements to remove from the array.
  • elementsToAdd: The elements to add to the array. Can be one or more elements, separated by commas.

Example:

let fruits = ["Apple", "Banana", "Cherry", "Durian"];
fruits.splice(2, 0, "Mango");
console.log(fruits);
// Output: ["Apple", "Banana", "Mango", "Cherry", "Durian"]

In this example, splice() is used to add “Mango” at index 2 without removing any elements.

Another example:

let fruits = ["Apple", "Banana", "Cherry", "Durian"];
fruits.splice(1, 2, "Mango");
console.log(fruits);
// Output: ["Apple", "Mango", "Durian"]

In this example, splice() is used to remove 2 elements starting from index 1 and add “Mango” at index 1.