There are several ways to empty an array in JavaScript. Here are some common methods:
1. Assign an Empty Array
You can assign a new empty array to the variable, effectively replacing the original array with an empty one.
Syntax:-
var arrayList=[];
Example:-
var array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var new_array_list = array_list; // Referenced arrayList by another variable
array_list = []; // Empty the array
console.log(array_list); //Output []
console.log(new_array_list); // Output ['a', 'b', 'c', 'd', 'e', 'f']
Note:- if you changed original array variable then reference array will remain unchanged.
2. Set the Length to Zero
Setting the length property of the array to 0 will clear all elements.
Syntax:-
var arrayList.length=0;
Example:-
var array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var new_array_list = array_list; // Referenced array_list by another variable
array_list.length = 0; // Empty the array by setting length to 0
console.log(array_list); // Output []
console.log(new_array_list); // Output []
Note:- This way of empty the array also update all the reference variable which pointing to the original array.
3. Use the splice() Method
You can use the splice() method to remove all elements from the array.
Syntax:-
arrayList.splice(0, arrayList.length);
Example:-
var array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var new_array_list = array_list; // Referenced array_list by another variable
array_list.splice(0, array_list.length); // Empty the array by setting length to 0
console.log(array_list); // Output []
console.log(new_array_list); // Output []
4. Pop Elements Until Empty
You can use a loop to pop elements from the array until it is empty. This method might not be as efficient as others but works effectively.
let array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
while (array_list.length > 0) {
array_list.pop();
}
console.log(array_list); // Outputs: []
5. Shift Elements Until Empty
Similar to pop
, you can use a loop to shift elements from the front of the array until it’s empty.
let array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
while (array_list.length > 0) {
array_list.shift();
}
console.log(array_list); // Outputs: []