How to empty a JavaScript array.

This is a short tutorial on how to empty a JavaScript array. To be honest, the solution to this is so simple that you might kick yourself for not thinking of it sooner!

The quickest way to empty a JavaScript array is to simply overwrite the variable with a new blank array. Take the following example:

//Example JavaScript array.
var myArray = ['test', 'test2', 'hello'];

//Log the array to our browser console so that
//we can see it's structure.
console.log(myArray);

//Empty the array by overwriting it with
//a new empty array.
myArray = [];

//Log it to the console again so that
//you can see it is empty.
console.log(myArray);

In the code above, we:

  1. Created a JavaScript array that contains three elements.
  2. We then logged that array to the browser’s console so that we could view it’s structure.
  3. Then, we overwrote the original array with a new blank array.
  4. Finally, we logged it to the developer console again.

If you run the code above and look at your browser’s developer console, you should see something similar to this:

emptying an array in javascript

As you can see, our JavaScript array has been completely emptied.

Note that this is both the fastest and easiest solution to this problem.