How to Empty an Array in JavaScript

Updated onbyAlan Morel
How to Empty an Array in JavaScript

Sometimes when you're working with an array, you'll want to empty it out, or clear it out.

Doing so allows you to not have to define a new variable, and then fill in your empty array with new elements in the future.

In this post, we'll look at all the ways to empty an array in JavaScript.

How to empty an array in JavaScript

Let's say you have this array:

JAVASCRIPT
let array = [1, 2, 3, 4, 5];

The easiest way to empty it out is to just re-assign it an empty array:

JAVASCRIPT
let array = [1, 2, 3, 4, 5]; array = []; console.log(array);
JAVASCRIPT
[]

This method works best when this array was not used as a reference for another array.

Another common way to empty out an array is to just update its length to 0.

JAVASCRIPT
let array = [1, 2, 3, 4, 5]; array.length = 0; console.log(array);
BASH
[]

The reason this method works is because when you update the length of an array, it will automatically re-size the array to the new length, meaning if you decrease the length, it will remove the elements from the end of the array.

Alternatively, if you want to clear out the array while also returning all of the cleared elements, you can just splice out the entire array using slice() and passing in the first and last indexes as the parameters.

JAVASCRIPT
let array = [1, 2, 3, 4, 5]; const contents = array.splice(0, array.length); console.log(array); console.log(contents);
BASH
[] [1, 2, 3, 4, 5]

Conclusion

In this post, we learned at several ways to empty an array in JavaScript.

You can either re-assign it to an empty array, or update its length to 0, or splice out the entire array.

Thanks for reading!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.