How to Empty an Array in JavaScript?
There are a number of ways to empty an array in JavaScript, probably the simplest is to reassign the variable to an empty array:
let array = [1, 2, 3];
// Assigning to an empty array
array = [];
You can also set the length of the array to 0:
// Setting its length property to 0
array.length = 0;
Splice can be also used get rid of everything from an array:
// Using splice with the array's length
array.splice(0, array.length);
So which one to use? The simplest, and also the fastest operation is simply reassigning the variable to an empty array. To see the performance difference, checkout the 3 solutions on JSBen.
Resources:
Rocket Launch Your Career
Speed up your learning progress with our mentorship program. Join as a mentee to unlock the full potential of Webtips and get a personalized learning experience by experts to master the following frontend technologies: