Empty Array in JavaScript

- 1 minute read

One common way to empty a JavaScript array is by setting its length property to 0:

const array = [1, 2, 3];

array.length = 0;

console.log(array); // Logs "[]"

The above solution is actually not the fastest. The below solution is the most performant:

let array = [1, 2, 3];

array = [];

console.log(array); // Logs "[]"

However, there are two reasons why I don’t use the above solution and instead set the length to 0:

  1. If the array is declared using const, then setting the array to [] will not work. It must be declared using let or var instead.

  2. If “Array B” references “Array A”, and Array A is emptied by being set to [], then Array B will not be automatically emptied as well.

Link to this section Conclusion

Anyway, those are a few of the simplest methods by which JavaScript arrays can be emptied.