How do I empty an array in JavaScript?

JavaScript, Array · Jun 12, 2021

When working with JavaScript arrays, a pretty common question is how does one empty an array and remove all its elements. As it turns out, there are a few ways you can go about this, each one with its pros and cons.

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 const.

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 const variables.

let a = [1, 2, 3, 4];
a.length = 0;

Use Array.prototype.splice()

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

Use Array.prototype.pop()

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

I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.

If you want to keep in touch, follow me on GitHub or Twitter.

More like this

  • How do I compare two arrays in JavaScript?

    Learn how you can compare two arrays in JavaScript using various different techniques.

    JavaScript, Array · Sep 27, 2021

  • Initialize array with range

    Initializes an array containing the numbers in the specified range where start and end are inclusive with their common difference step.

    JavaScript, Array · Oct 22, 2020

  • Initialize array with reversed range

    Initializes an array containing the numbers in the specified range (in reverse) where start and end are inclusive with their common difference step.

    JavaScript, Array · Oct 20, 2020