AppDividend
Latest Code Tutorials

Javascript Clear Array: How to Empty Array in Javascript

0

JavaScript arrays enable you to group values and iterate over each item. You can append and remove array elements in different ways. Unfortunately, there is not a simple Array.proptotype.clear method to clear the whole array. To clear array in Javascript, there are multiple ways.

Javascript clear array

To clear array in Javascript, there are multiple ways to do that.

  1. Substituting an existing array with a new array.
  2. Setting an array length prop to 0.
  3. Splice the whole array.

Substituting an existing array with a new array

The fastest way to clear or empty an array in Javascript is substituting an existing array with a new empty array. See the following code.

dark = ['jonas', 'martha', 'claudia']
console.log(dark)
console.log('After substituting array with empty array')
dark = []
console.log(dark)

Output

[ 'jonas', 'martha', 'claudia' ]
After substituting array with empty array
[]

You can see that we have defined an array dark with three elements and then empty that array by substituting with [ ]. This is the fastest way to empty an array in Javascript.

The dark = [ ] assigns a reference to a new array to a variable. In contrast, any other references are unaffected, which means that references to the contents of a previous array are still kept in the memory, leading to memory leaks.

Setting an array length to 0

To clear an array, convert the array length to 0. This way, array can’t have a single item, and it will automatically be cleared. It removes each item in the array, which does hit other references.

In other words, if you have two references to the same array (a = [11, 21, 46]; a2 = a;), and you delete the array’s contents using an array.length = 0, both references (a and a2) will now point to the same empty array.

let data = [11, 21, 46];
let set = [11, 21, 46];
let data2 = data;
let set2 = set;
data = [];
set.length = 0;
console.log(data, set, data2, set2);

Output

[] [] [ 11, 21, 46 ] []

Empty array by Splice the whole array

To empty array in Javascript, splice the whole array using the Javascript array splice() method.

let data = [11, 21, 46];
data.splice(0, data.length)
console.log(data)

Output

[]

To use the splice() method, passing first argument as 0 and array length as the second parameter. This will return the copy of the original elements, which may be handy for some scenario but it will remove all items from the array and will clean the original array.

That is it for cleaning an array in Javascript.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.