There are various methods to empty an array in JavaScript.
1. Setting the Length Property to 0
The length
property of an array defines the number of elements in the array. Setting it to 0
effectively clears all elements.
let arr = [10, 20, 30, 40, 50]; arr.length = 0; // Clears the array console.log(arr); // Output: []
2. Reassigning to an Empty Array
You can replace the existing array with a new empty array using assignment.
let arr = [10, 20, 30, 40, 50]; arr = []; // Reassigns the array console.log(arr); // Output: []
Note: The original array reference remains unchanged, but other references pointing to the old array will not reflect the update.
3. Using splice() Method
The splice()
method can remove all elements of the array by starting at index 0
and removing its entire length.
let arr = [10, 20, 30, 40]; arr.splice(0, arr.length); // Clears the array console.log(arr); // Output: []
4. Using pop() in a Loop
You can repeatedly use the pop()
method to remove elements from the end of the array until it becomes empty.
let arr = [10, 20, 30, 40, 50]; while (arr.length > 0) { arr.pop(); } console.log(arr); // Output: []
5. Using shift() in a Loop
Similar to pop()
, you can use shift()
to remove elements from the beginning of the array until it’s empty.
let arr = [10, 20, 30, 40, 50]; while (arr.length > 0) { arr.shift(); } console.log(arr); // Output: []