Empty an Array with JavaScript

Empty an Array with JavaScript is the common task which every developer performs. Most of the developers use the wrong approach of emptying the array in JS.

Method 1: Empty an Existing Array in JavaScript

This is the easiest way to empty an array but it’s not the optimal way to do it. This is perfect if you don’t have references to the original array. The best way to empty an array is to set the length property to 0.

Method 2: Empty an Array using JavaScript

The right way to Empty an array is to set the array length to 0. This is the optimal and fastest way to clear an array. Check out the below example for clearing the array in a right way.

Another approach is to use Array.Splice() method which works perfectly. Some developers say this has performance issues since it returns the copy of the array which is been removed. The actual benchmark suggests there are no performance issues with this approach.

Method 3: Remove all the elements from an Existing Array using Array.Splice() Method

Array.Splice() Method works perfectly and it is another easiest way to empty an array. All you need to give the start index as 0 and the delete count as array length. Check out the below example of removing all the elements from an array.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *