How to Clear an Array in JavaScript (JS)

This minHour 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

Replace 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. For example, let’s say your array looks like this: let a = [1,2,3];. To assign a to a new empty array, you’d use:

  • a = [];

Set 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;

Splice 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. 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);

Leave a Comment