# How to add, remove, and replace items using Array.splice() in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jun 3, 2020. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-array-splice

> A complete guide to learn how to use the Array.splice() method in JavaScript to add, remove, or replace elements in an array.

In JavaScript, the `Array.splice()` method can be used to add, remove, and replace elements from an array. This method modifies the contents of the original array by removing or replacing existing elements and/or adding new elements in place. `Array.splice()` returns the removed elements (if any) as an array.

## Syntax

Here is the syntax of `Array.splice()`:

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

* `start` &mdash; The starting index for changing elements in the array.
* `deleteCount` &mdash; An integer indicating the number of elements in the array to remove from `start`. If `deleteCount` is `0` or negative, no elements are removed. In this case, you have to specify at least one new element.
* `item1, item2, ...` &mdash; The elements to be added to the array, beginning from `start`. If no elements are specified, `splice()` will only remove elements from the array.

## Removing Elements

Here is example that uses `Array.splice()` to remove first two elements from the beginning of an array:

```javascript
const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

// remove first elements
const removed = fruits.splice(0, 2);

console.log(fruits); // ['Mango', 'Banana']
console.log(removed); // ['Apple', 'Orange']
```

If the `deleteCount` is omitted, all the elements starting from `start` are removed from the array:

```javascript
const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

const removed = fruits.splice(1);

console.log(fruits); // ['Apple']
console.log(removed); // ['Orange', 'Mango', 'Banana']
```

## Replacing Elements

You can also replace the removed items with the new one by using `Array.splice()`:

```javascript
const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

const removed = fruits.splice(1, 2, 'Cherry', 'Watermelon');

console.log(fruits); // ['Apple', 'Cherry', 'Watermelon', 'Banana']
console.log(removed); // ['Orange', 'Mango']
```

## Adding Elements

To add new elements with `Array.splice()`, just set the `deleteCount` to zero and pass new items:

```javascript
const fruits = ['Apple', 'Orange', 'Mango', 'Banana'];

const removed = fruits.splice(2, 0, 'Cherry');

console.log(fruits); // ['Apple', 'Orange', 'Cherry', 'Mango', 'Banana']
console.log(removed); // []
```

## Browser Compatibility

The `Array.splice()` method works in all modern browsers, and IE6 and above.

To learn more about JavaScript arrays and how to use them to store multiple pieces of information in one single variable, take a look at [this guide](https://attacomsian.com/blog/javascript-arrays).
