One of the easiest ways to empty a JS array is to set its length to zero. Alternatively you can use the functions pop
or splice
.
Empty a JavaScript array by setting its length to 0
The length
property holds the size of an array in JS. By setting it to zero, you’re effectively emptying the array.
const arr = [1, 2, 3];
arr.length = 0;
console.log(arr); // []
Empty a JavaScript array with splice
The function splice
removes all the elements from a JS array if you call it with 0 as a first argument and
array length as a second one.
const arr = [1, 2, 3];
arr.splice(0, arr.length);
console.log(arr); // []
Empty a JavaScript array with pop
in a while
loop
This method of emptying a JS array is a bit weird, and I wouldn’t recommend using it unless you absolutely have to. The while loop will have to spin for however many elements you have in the array, which will degrade performance for longer arrays.
const arr = [1, 2, 3];
while (arr.length > 0) {
arr.pop();
}
console.log(arr); // []