Clearing Arrays in JavaScript

To clear an array in JavaScript, you can assign a new empty array "[]" to it or set the length of the array to zero (array.length = 0). The first way is the fastest, and it's handy if you don't have references to the original array anywhere else because it creates a whole new (empty) array. You must be careful with this method because the original array will remain unchanged if you refer to this array from another variable or property. The second way will clear the existing array by setting its length to 0. The length property is a read/write property of the array object, and when set to zero, all array elements are automatically removed. In this JavaScript array clearing example, we are assigning a new empty array "[]" to an existing variable. Below you can see more examples of JavaScript array clearing with a detailed description of each method. Click Execute to run the JavaScript Clear Array Example online and see the result.
Clearing Arrays in JavaScript Execute
let array = ['JavaScript', 'Clear', 'Array', 'Example'];

array.length = 0;

console.log(array.length);
Updated: Viewed: 4709 times

Clear array using replacing with a new array

You can clear an array by replacing it with a new empty array. This is the fastest way if you don't have references to the original array anywhere else because a new empty array is created.

JavaScript Array Clear Example
let array = ['JavaScript', 'Clear', 'Array', 'Example'];

array = [];

console.log(array.length);

// output: 0

Clear array using the length property

You can clear an array using the length property, which returns the number of elements in that array. All array elements are automatically removed when the length property is set to zero. This method is quite popular but not the fastest way to get the job done.

JavaScript
let array = ['JavaScript', 'Clear', 'Array', 'Example'];

array.length = 0;

console.log(array.length);

// output: 0

See also