| |
|
Different method to empty an Array in JavaScript? Question Posted on 14 Apr 2022 Home >> JavaScript >> Javascript Code >> Different method to empty an Array in JavaScript? |
Different method to empty an Array in JavaScript?
Below are the different 4 methods to empty an Array in JavaScript:-
Method 1
Below method will set the variable arrayList to a new empty array. And it is recommended to use it if you donot have references to original array arrayList anywhere else. Because this will create a new empty array. Be careful with method of empty array because if you reference array from another variable then the orginal reference array will remain unchanged. Syntax for above is:-
arrayList=[]
Method 2
Below method will clear the existing array by setting its length to 0. And another important facts about this emptying array is that it will updates all the reference variable which point to original array. So this method is useful when we want to update all reference variable pointing to arrayList. Below is the syntax:-
arrayList.length=0;
Method 3
Below method will do the same as above method 2 this will empty the array and also update all the references to original array. And syntax of above method:-
arrayList.splice(0, arrayList.length);
Method 4
This method will empty array but is not recommended to use this method.
while(arrayList.length)
{
arrayList.pop();
} | |
|
|
|
|