JavaScript - how to empty array
In this article, we would like to show you how to empty array in JavaScript.
Below examples show four solutions on how to do that:
- By setting the array to a new empty array,
- By setting the array's
length
to 0, - By using
splice()
method, - By using
while
loop.
1. Setting the array to a new empty array
In this solution, we set the existing variable to a new, empty array. To see if the array has been cleared, we display the result.
Runnable example:
// ONLINE-RUNNER:browser;
var array = [1,2,3];
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.
2. Setting the array's length to 0
In this solution, we empty the existing array by setting its length
to 0
.
To see if the array has been cleared, we display the result.
Runnable example:
// ONLINE-RUNNER:browser;
var array = [1,2,3];
array.length = 0; // <----------
console.log(array.length); // 0
3. Using splice()
method
In this solution we use .splice()
method to remove every item from index 0
to array.length
.
To see if the array has been cleared, we display the result.
Runnable example:
// ONLINE-RUNNER:browser;
var array = [1,2,3];
array.splice(0, array.length); // <----------
console.log(array.length); // 0
Note:
.splice()
function will return an array with all the removed items.Click here to read more about splice() method.
4. Using while
loop
In this solution we use while
loop to pop()
every single item from an array.
To see if the array has been cleared, we display the result.
Runnable example:
// ONLINE-RUNNER:browser;
var array = [1,2,3];
while(array.length > 0) { // <----------
array.pop();
}
console.log(array.length); // 0
Note:
This solution is the slowest from all of the above.