This article was co-authored by wikiHow staff writer, Nicole Levine, MFA. Nicole Levine is a Technology Writer and Editor for wikiHow. She has more than 20 years of experience creating technical documentation and leading support teams at major web hosting and software companies. Nicole also holds an MFA in Creative Writing from Portland State University and teaches composition, fiction-writing, and zine-making at various institutions.
This article has been viewed 15,254 times.
Learn more...
This wikiHow teaches you how to empty a JavaScript array. There are three primary ways to clear an array—replacing the array with a new array, setting its property length to zero, and splicing the array. These three methods work similarly, although replacing the array with a new array (the fastest method) shouldn't be used if other code references the original array.
Steps
-
1Replace the array with a new array. This is the fastest way to clear an array, but requires that you don't have references to the original array elsewhere in your code.[1] For example, let's say your array looks like this:
let a = [1,2,3];
. To assigna
to a new empty array, you'd use:a = [];
-
2Set the length property to zero. An alternative to replacing the array with a new array is setting the array length to 0. This will work even if you have references to the original array elsewhere, but it won't free objects from memory, which may slightly affect performance. To set the "a" array to zero, use the following code:
a.length = 0;
Advertisement -
3Splice the array. A third way to clear an array is to use
.splice()
. Splicing won't be as fast as the other two methods because it will return the removed elements as an array.[2] It will, however, always work to clear the original array, regardless of references. To splice the array "a"," you'd use this code:a.splice(0, a.length);
References
About This Article
Option 1: Replace the array with a new array.
Option 2: Set the length property to 0.
Option 3: Splice the array.