In this short snippet, you will learn How to Empty an Array in Javascript the easy way. Let's get started.
Method 1 - Using Array Splice
const array = [1, 2, 3, 4, 5];
array.splice(0);
console.log(array); // -> []
The splice(0) method will remove array from 0 to end
Method 2 - Length Trick
const array = [1, 2, 3, 4, 5];
array.length = 0;
console.log(array); // -> []
Extra Notes
If there is only one reference to the array, you may also want to assign a new array to the variable. The old array would be garbage collected.
let array = [1, 2, 3, 4, 5];
array = [];
However this will cause an issue if there are more than one reference to the same array.
let array = [1, 2, 3, 4, 5];
let array2 = array;
array = [];
console.log(array2); // -> [1, 2, 3, 4, 5];
Leave a reply