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

//Creating an Array in JavaScript
var names=['Jack','Rob','Bill'];

//Wrong way of Emptying Array in JavaScript
names=[];

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.

//Creating an Array using JavaScript
var names=['Jack','Rob','Bill'];

//Right way of Emptying Array in JavaScript
names.length=0;

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.

//Creating an Array in JavaScript
var names=['Jack','Rob','Bill'];

//Right way of Emptying Array in JavaScript
names.splice(0,names.length);

0 Shares
Leave a Reply

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

You May Also Like
XOR in Python

XOR in Python

XOR Operator in Python is also known as “exclusive or”  that compares two binary numbers bitwise if two bits are…
How To

How to configure Git proxy?

If you are working in the corporate company all the internet requests usually goes through the corporate firewall.…