# How to empty an array in JavaScript

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

> A quick guide to learn how to remove all elements of an array in vanilla JavaScript.

In JavaScript, there are multiple ways available to remove all elements of an array. The simplest method is to set the array's `length` property value to 0.

Here is an example:

```javascript
const numbers = [1, 2, 3, 4, 5, 6];

// set length to 0
numbers.length = 0;

console.log(numbers); // []
```

Since the `length` property is writable, the above example will clear all elements of the array. Also, it doesn't mutate the original array and works in all modern and old browsers including Internet Explorer.

Another way to remove all elements of an array is by assigning an empty array to the original variable:

```javascript
let numbers = [1, 2, 3, 4, 5, 6];

// reset array
numbers = [];

console.log(numbers); // []
```

You should only use this method when you are sure that the original array is **not referenced** anywhere else in the code because this actually creates a brand new empty array. If you are referencing the original array from another variable or property, the original array will remain unchanged. Therefore, you should be careful while using this method. 

Here is an example that demonstrates the issue you may encounter when assigning a new array to an already existing array:

```javascript
let numbers = [1, 2, 3, 4, 5, 6];

let numbers2 = numbers; // store original array reference

// reset original array
numbers = [];

// print reference variable
console.log(numbers2); // [1, 2, 3, 4, 5, 6]
```

The `splice()` method is yet **another way** to empty an array in JavaScript:

```javascript
let numbers = [1, 2, 3, 4, 5, 6];

// empty the array
numbers.splice(0, numbers.length);

console.log(numbers); // []
```

You can also add a new method to `Array`'s [prototype](https://attacomsian.com/blog/objects-prototypes-classes-javascript#prototypes) and use it whenever you want to clear an array:

```javascript
// add prototype method
Array.prototype.clear = function () {
    this.length = 0;
};

let numbers = [1, 2, 3, 4, 5, 6];

// clear arary
numbers.clear();

console.log(numbers); // []
```

Take a look at [this guide](https://attacomsian.com/blog/javascript-arrays) to learn more about JavaScript arrays and their methods.
