This content originally appeared on Go Make Things and was authored by Go Make Things
Today, we’re going to look at two different ways to empty an array with JavaScript. Let’s dig in!
Reassigning the variable
Let’s say you have an array of wizards, like this.
let wizards = ['Gandalf', 'Radagast', 'Merlin'];
You want to completely wipe it out. The most common way to do this is to reassign the value of the wizards
variable to an empty array ([]
).
wizards = [];
Setting the length
to 0
Another way to clear an array is to set the array’s length
property to 0
.
wizards.length = 0;
(Thanks to Kitty Giraudel for this tip.)
Why would you set the length
instead of reassigning the variable?
In most situations, reassigning the variable to an empty array is the better choice. It’s shorter and more explicit than adjusting the length
property.
But sometimes, you have an array that’s assigned by reference, and you want to keep them linked.
Here, I have my array of wizards
. I also have an alsoWizards
variable, and I set its value to the wizards
array. The alsoWizards
array is not a copy of wizards
. It references the original array.
let wizards = ['Gandalf', 'Radagast', 'Merlin'];
let alsoWizards = wizards;
If I reassign the value of wizards
, the alsoWizards
variable still points to the original array that was assigned to it.
// Clear the array
wizards = [];
// logs []
console.log(wizards);
// logs ["Gandalf", "Radagast", "Merlin"]
console.log(alsoWizards);
You can see it in action here.
If I instead set the length
of wizards
to 0
, the alsoWizards
variable is also an empty array, because the array that wizards
points to has not changed.
// Clear the array
wizards.length = 0;
// logs []
console.log(wizards);
// logs []
console.log(alsoWizards);
This content originally appeared on Go Make Things and was authored by Go Make Things
Go Make Things | Sciencx (2022-01-07T15:30:00+00:00) Two ways to clear an array with vanilla JavaScript. Retrieved from https://www.scien.cx/2022/01/07/two-ways-to-clear-an-array-with-vanilla-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.