Want to clear an Array in JavaScript? Or looking for ways to empty Array? This quick tutorial will show you different ways to clear Array in JS.

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.

For example-


// 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.

Another way to empty an Array in JavaScript

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

The splice() method can be used to clear or empty the existing JavaScript array. For this, we need to pass to argument the starting index and the last index of the array.


// given array
var myArray=[1,2,3,4,5];

// clear the given array
myArray.splice(0,myArray.length);

console.log(myArray)  //[]

Conclusion

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.

Feel to check how to reverse an array in JavaScript.

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed.