JavaScript(JS) array method - splice

w‮i.ww‬giftidea.com

The splice() method in JavaScript is used to add or remove elements from an array. It can be used to add elements to an array, remove elements from an array, or even replace elements in an array. The method modifies the original array in place.

The syntax for the splice() method is as follows:

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

Here is what each of the parameters means:

  • start: The index at which to start changing the array. If the value of start is negative, the index is counted from the end of the array. If start is greater than the length of the array, no elements will be removed, but new elements will be added.
  • deleteCount: An optional integer value that specifies the number of elements to remove from the array. If deleteCount is 0 or negative, no elements will be removed. If deleteCount is greater than the number of elements between start and the end of the array, all elements from start to the end of the array will be removed.
  • item1, item2, ...: Optional values to add to the array, beginning at the start index. If no items are specified, splice() will only remove elements from the array.

Here are a few examples of using the splice() method:

const array = [1, 2, 3, 4, 5];

// Remove elements from the array
array.splice(2, 2); // Removes elements at index 2 and 3
console.log(array); // Output: [1, 2, 5]

// Add elements to the array
array.splice(2, 0, 3, 4); // Adds elements at index 2
console.log(array); // Output: [1, 2, 3, 4, 5]

// Replace elements in the array
array.splice(2, 2, "three", "four"); // Replaces elements at index 2 and 3
console.log(array); // Output: [1, 2, "three", "four", 5]

In the first example, the splice() method is used to remove two elements from the array starting at index 2. In the second example, the splice() method is used to add two elements to the array starting at index 2. In the third example, the splice() method is used to replace two elements in the array starting at index 2 with the strings "three" and "four".