The easiest way to clear an Array
The most simple and easy way to clear an array is to assign it with an empty array.
// given array var myArray=[1,2,3,4,5]; // clear the given array myArray=; console.log(myArray) //
In the above example, myArray contained values from 1 to 5. To clear or empty its values, we assigned it with a blank array(  ).
The initial value the array contained is now overwritten/ re-assigned with a blank array.
An alternative to the above method to clear an array is to make the array length zero. Here is how-
// given array var myArray=[1,2,3,4,5]; // clear the given array myArray.length=0; //setting the array length to zero console.log(myArray) //
We generally use array length to get/read the array length, but the same property can be used to set the length. Here in this case we have set it equal to 0, Making the existing array to size zero. In other words, the array values are cleared.
Using splice() method to clear Array
// given array var myArray=[1,2,3,4,5]; // clear the given array myArray.splice(0,myArray.length); console.log(myArray) //
You can use any of the above ways to empty the value of an array. And can use the array further to insert new values.
Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed.