What is the array.splice() method in JavaScript?

The splice() method in JavaScript updates the contents of an array by either removing or replacing existing elements and/or adding new elements. It modifies the original array and does not create a new array.

Syntax

array.splice(start, deleteCount, item1, item2, itemN)

Parameters

  • start: The index at which the array will start changing.
  • deleteCount (Optional): The number of elements in the array to remove, starting from the start index.
  • item1, item2, ... itemN (Optional): The items to be added to the array, beginning from the start. If no element is defined, splice() will only remove elements from the array.

Return value

The splice() function modifies the array in-place. However, the function still returns an array containing the deleted elements. If nothing is deleted, then it returns an empty array.

Code

let countries = ['TOGO', 'GHANA', 'BENIN', 'MALI', 'CAMEROON']
let removed = countries.splice(3, 1)
console.log(removed) // Expected output: [ 'MALI' ]
console.log(countries) // [ 'TOGO', 'GHANA', 'BENIN', 'CAMEROON' ]
let added = countries.splice(2, 0, 'KENYA')
console.log(added) // Expected output: []
console.log(countries) // Expected output: [ 'TOGO', 'GHANA', 'KENYA', 'BENIN', 'CAMEROON' ]

Explanation

In the code above we have two examples, each using different approaches. When we call the splice() method on an array and print its value, it returns a new array based on the specified condition. This process also affects the original array.

Free Resources