Introduction
This article will teach us the best way to delete a JavaScript array.
I have seen many programmers deleting arrays in JavaScript using the following code or something similar.
var arr=[1,2,3,4,5];
console.log(arr);// It will print [1,2,3,4,5]
arr=[];
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.
var arr1=[1,2,3,4,5]
var arr2=arr1;
console.log(arr1);// It will print [1,2,3,4,5]
console.log(arr2);// It will print [1,2,3,4,5]
arr1=[];
console.log(arr1);// It will print []
console.log(arr2);// It will print [1,2,3,4,5]
Note
When you do arr = [ ], JavaScript assigns the variable a reference to a new array. However, any other object that refers to the same array is unaffected. 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. Always use the following code when you want to delete everything in the array.
arr.length = 0
It will delete the other references as well.
Example
var arr1=[1,2,3,4,5]
var arr2=arr1;
console.log(arr1);// It will print [1,2,3,4,5]
console.log(arr2);// It will print [1,2,3,4,5]
arr1.length=0;
console.log(arr1);// It will print []
console.log(arr2);// It will print []
Summary
Always remember to use arr when deleting a complete array with all the references.length=0, Otherwise, use arr=[ ].
Happy Coding :)