Borislav Hadzhiev
Mon Oct 11 2021·2 min read
Photo by Hamid Tajik
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.
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.
For our purposes we provide a start index of 0
to delete all elements and
empty 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.
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.
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.