Home » Programming » Javascript » Javascript Reset Clear Array

How to Reset/Clear/Empty an Array in JavaScript

This quick article will show you the right way to reset/clear/empty an array in the JavaScript programming language.

The Right Way to Reset/Clear/Empty an Array – Set the length to 0

This is the best way to reset/clear/empty an array in JavaScript. It is unambiguous and will affect both the variable containing the array and any variables referencing the array.

var myArray = [1, 2, 3, 4];
myArray.length = 0;

Above, an array is declared and then emptied by setting the array’s length property to 0.

The Wrong Way – Re-declare the Variable

This is not the best way to do this!

A common approach to resetting an array is to re-declare it with an empty array – replacing the current value of the array with an empty one.

var myArray = [1, 2, 3, 4];
myArray = [];

This is a bad idea – it’s possible (and likely) that any existing references to the array will still point to an instance of the variable while it was populated and retain that value even after the original array is re-declared to an empty array.

Play it safe and use the Array.length property to clear the array, as outlined above, instead. It’s always good to know exactly what your code is doing without any ambiguity.

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment