Choose The Best Way To Delete An Array In JavaScript

Introduction

In this article, we will learn the best way to delete a JavaScript array.
 
I have seen  lots of programmers deleteing arrays in JavaScript using the the following code or something similar to it.
  1. var arr=[1,2,3,4,5];  
  2. console.log(arr);// It will print [1,2,3,4,5]  
  3.   
  4. arr=[];  
  5. console.log(arr);// It will print []  
Generally, developers think they have deleted all the items of the array.

 
 
Now, let's look into the next example.
  1. var arr1=[1,2,3,4,5]  
  2. var arr2=arr1;  
  3. console.log(arr1);// It will print [1,2,3,4,5]  
  4. console.log(arr2);// It will print [1,2,3,4,5]  
  5.   
  6. arr1=[];  
  7. console.log(arr1);// It will print []  
  8. console.log(arr2);// It will print [1,2,3,4,5]  
 
 
Note
When you do arr = [ ] then JavaScript assigns the variable a reference to a new array, however, any other object that refers to the same array is not affected. It means the data is still kept in memory.
 
What is the best way to delete a JavaScript array?

arr = [] assigns the variable a reference to a new array. When you want to delete everything in the array, always use the following code.
  1. arr.length = 0  
It will delete the other references as well.
 
Example
  1. var arr1=[1,2,3,4,5]  
  2. var arr2=arr1;  
  3. console.log(arr1);// It will print [1,2,3,4,5]  
  4. console.log(arr2);// It will print [1,2,3,4,5]  
  5.   
  6. arr1.length=0;  
  7. console.log(arr1);// It will print []  
  8. console.log(arr2);// It will print []  
 
 
Always remember, when you want to delete a complete array with all the references, use arr.length=0, Otherwise, use  arr=[ ].
 
Happy Coding :)