How to Empty an Array in JavaScript?
To empty an array in JavaScript, we can use the array literal. We can directly assign an empty array literal to the variable, it will automatically remove all the elements and make the array empty.
1. Empty Array using Array Literal
We can empty the array using the empty array literal syntax.
Syntax
arr = [ ];
// Given array
let a = [ 10, 20, 30, 40, 50 ];
// Assign new array to make it empty
a = [];
// Display the updated array
console.log("Updated Array: ", a)
Output
Updated Array: []
2. Using array.length Property
The JavaScript array.length property is used to set or return the length of the array.
Syntax
arr.length = 0;
// Given array
let a = [ 10, 20, 30, 40, 50 ];
// Empty the array by setting its length to 0
a.length = 0;
// Display Updated array and its length
console.log("Updated Array: ", a);
console.log("Length of Updated Array: ", a.length);
Output
Updated Array: [] Length of Updated Array: 0
3. Using array.splice() Method
The JavaScript array.splice() method is used to remove elements from certain index and add new elements to the array.
Syntax
arr.splice(0);
It will start removing elements from 0 index and as the number of elements is not given it will remove all elements present in the array.
// Given array
let a = [ 10, 20, 30, 40, 50 ];
// Remove elements using array.splice() method
a.splice(0);
// Display the updated array
console.log("Updated Array: ", a)
Output
Updated Array: []
4. Using array.pop() Method
The JavaScript array.pop() method is used to remove the elements one by one from the array.
Syntax
arr.pop();
// Given array
let a = [ 10, 20, 30, 40, 50 ];
// While loop to iterate
while( a.length > 0){
// Remove the last element in
// each iteration
a.pop()
}
// Display the updated array
console.log("Updated Array: ", a)
Output
Updated Array: []
Note: Array clearing techniques in JavaScript is essential for effective data management.