Assign it to an empty array
You can assign your variable to an empty array (
) in order to clear it. While this option is rather fast, you should be mindful of references to the original array, as they will remain unchanged. Moreover, it doesn't work for arrays declared as
let a = [1, 2, 3, 4]; a = ;
Set its length to 0
A better option is to set the
length of the array to
0. This option is also pretty fast and has the additional benefit of working for
let a = [1, 2, 3, 4]; a.length = 0;
Array.prototype.splice() can also be a useful alternative when trying to empty an array. While it has no other downsides compared to the previous method, it doesn't seem to perform as well, so that might be something to consider.
let a = [1, 2, 3, 4]; a.splice(0, a.length);
Last but not least, using
Array.prototype.pop() is another, more old-fashioned option. It's generally more verbose and less performant, so I'd rather use one of the previous methods instead.
let a = [1, 2, 3, 4]; while (a.length) a.pop();
Written by Angelos Chalaris
If you want to keep in touch, follow me on GitHub or Twitter.