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 = ;
Another way to clear an array is to set the array’s
length property to
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
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
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
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);