Empty an Array in JavaScript
How can you empty an array in JavaScript?
Let's go over three different ways to do this.
Method 1: Set the Array to a New Empty Version
array = [];
This sets your existing array to a new empty version.
For example, here's a full version of how it would be used:
let array = ["value", "value", "value"];
array = [];
// array will now be empty
Method 2: Give the Array a Length of Zero
This will also clear an array:
array.length = 0;
This clears the array by setting its length property to 0
.
For example, here's a full version of how it would be used:
let array = ["value", "value", "value"];
array.length = 0;
// array will now be empty
Method 3: Splice the Entire Array
If you splice() from the beginning to the end of the array, all items in the array will be removed:
array.splice(0, array.length);
For example, here's a full version of how it would be used:
let array = ["value", "value", "value"];
array.splice(0, array.length);
// array will now be empty
Thanks for reading and happy coding!