Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript
array

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

Chibuike Nwachukwu

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

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.

RELATED TAGS

javascript
array

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring