How to empty an array in 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:

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:

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:

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:

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 and use it whenever you want to clear an array:

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

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

// clear arary

console.log(numbers); // []

Take a look at this guide to learn more about JavaScript arrays and their methods.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.