Posts Learn Components Snippets Categories Tags Tools new About
/

How to Empty an Array in Javascript

Learn how to How to Empty an Array in Javascript the easy way

Created on Jun 23, 2022

6 views

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];

If you like our tutorial, do make sure to support us by being our Patreon or buy us some coffee ☕️

Load comments for How to Empty an Array in Javascript

)