How to Empty an Array in JavaScript

avatar

Borislav Hadzhiev

Mon Oct 11 20212 min read

banner

Photo by Hamid Tajik

Empty an Array in JavaScript #

To empty an array, call the splice() method, passing it 0 as a parameter - splice(0). The method will empty the original array, by removing and returning all its elements starting at index zero.

index.js
const arr = ['a', 'b', 'c']; arr.splice(0); console.log(arr); // ๐Ÿ‘‰๏ธ []

The parameter we passed to the Array.splice method is the start index - the index at which we start changing the array.

The second parameter the splice method takes is delete count - the number of elements that should be removed from the array, from the start index onwards.

If the delete count parameter is not provided, all elements from the start index onwards get deleted.

For our purposes we provide a start index of 0 to delete all elements and empty the array.

A more performant and better solution is to reassign the variable holding the array.

To empty an array, reassign the variable storing the array and set it to an empty array, e.g. arr = []. Note that you can only reassign variables, declared using the let and var keywords. This is the most performant way to empty an array in JavaScript.

index.js
let arr = ['a', 'b', 'c']; arr = []; console.log(arr); // ๐Ÿ‘‰๏ธ []

Notice that we use the let keyword to to declare the arr variable. Had we used the const keyword, we wouldn't be able to reassign the variable and set it to an empty array.

An alternative approach is to set the array's length to 0.

To empty an array, set its length property to 0. When the length property of an array is changed, every element which has an index that is not smaller than the new length of the array gets automatically deleted.

index.js
const arr = ['a', 'b', 'c']; arr.length = 0; console.log(arr); // ๐Ÿ‘‰๏ธ []

By setting the array's length to 0, we automatically delete all elements from the array with an index that is not smaller than 0, which covers the entire array.

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee