How to empty an array in JavaScript ?

MoreOnFew
Posted underJavascript

Arrays are widely and commonly used in JavaScript. Especially if you are developing a dynamic app, there are very high chances that you might use Arrays in JavaScript. However, many a times I’ve noticed that people don’t use the Array related methods properly and end up doing certain things in a wrong way. One such example is, how to remove all items from array in javascript .

While there are various solutions available over the internet, I believe the following approach is good enough for most of the scenarios.

How to Clear or Empty an array in JavaScript ?

One of the most common ways people use to clear an Array in JavaScript is by assigning it a blank value. For e.g someArray = [] . This is a bad way to empty an array in JavaScript because it would technically create a new array. Instead, you should ideally set the length of the array to zero like :

someArray.length = 0;

Setting the length of an Array to zero would clear the existing array and avoids creating a new array. This would be helpful especially if you had a reference to the old array in some other array variable . For e.g :

Array_A = ['Green','Blue','Red','Yellow'];
Array_B = Array_A;
Array_A = [];
console.log(Array_B) // Prints ['Green','Blue','Red','Yellow']

/* Better way to do it. */
Array_A = ['Green','Blue','Red','Yellow'];
Array_B = Array_A;
Array_A.length = 0;
console.log(Array_B); // Prints []

Hope you found this article helpful. Please do like us on facebook and follow us on Twitter.

TaggedArrayArray MethodsJavascript


MoreOnFew.com – Read tutorials related to JavaScript, jQuery, HTML5, CSS3 and more !

Cover Image for How to check if checkbox is checked in jQuery?

How to check if checkbox is checked in jQuery?

It is very easy to check if a checkbox is checked in jQuery using the .is() or .prop() method of jQuery combined with the ‘:checked’ selector. There are other ways too like checking for the attribute checked value, however, they aren’t very reliable. The easiest and most stable way to check if checkbox is checked … Read more

MoreOnFew
Cover Image for [Solved] Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’

[Solved] Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’

You might be facing an “Attempted import error: ‘Switch’ is not exported from ‘react-router-dom’ ” error if you are using the react-router-dom package version 6. This error is caused due to using the older switch syntax of the react-router-dom. From version 6 onwards, the react-router-dom has replaced “Switch” with “Routes”. Let us take a look … Read more

MoreOnFew