JavaScript - how to empty array
In this article, we would like to show you how to clear / empty an array in JavaScript.
Quick solution:
xxxxxxxxxx
array.splice(0, array.length);
There are available following ways to clear the array:
- by setting the empty array as a variable value,
- by setting the array's
length
to0
, - by using
splice()
method, - by using
pop()
method inwhile
loop.
In this solution, we set the existing variable to a new empty array.
Runnable example:
xxxxxxxxxx
var array = [1, 2, 3];
array = []; // <---------- new empty array
console.log(array.length); // 0
Note:
You should be careful using this method, because if you have referencedarray
from another variable or property, the original array will remain unchanged.
In this solution, we empty the existing array by setting its length
to 0
.
Runnable example:
xxxxxxxxxx
var array = [1, 2, 3];
array.length = 0; // <---------- array size reset that clears array
console.log(array.length); // 0
In this solution we use splice()
method to remove every item from index 0
to array.length
.
Runnable example:
xxxxxxxxxx
var array = [1, 2, 3];
array.splice(0, array.length); // <---------- removes all items
console.log(array.length); // 0
Note:
splice()
method will return an array with all the removed items.Click here to read more about
splice()
method.
In this solution we use while
loop to pop()
every single item from an array.
Runnable example:
xxxxxxxxxx
var array = [1, 2, 3];
while (array.length > 0) {
array.pop(); // <---------- each iteration removes one item
}
console.log(array.length); // 0
Note:
This solution is the slowest from all of the above.