To empty an array in JavaScript, you can use one of the following methods, depending on your needs:
1. Set length = 0
(Fastest, Mutates Original Array)
Resets the array length to 0, clearing all elements.
Use this if other references to the array should also reflect the change.
let arr = [1, 2, 3];
arr.length = 0; // arr becomes []
2. Reassign to a New Empty Array
Creates a new empty array and reassigns the variable.
Use this if there are no other references to the original array.
let arr = [1, 2, 3];
arr = []; // arr now points to a new empty array
3. Use splice()
(Mutates Original Array)
Removes all elements from the array using splice
.
let arr = [1, 2, 3];
arr.splice(0, arr.length); // arr becomes []
4. Loop and Remove Elements (Not Recommended)
Inefficient for large arrays, but works:
let arr = [1, 2, 3];
while (arr.length > 0) {
arr.pop();
}
Key Differences
Method | Mutates Original Array | Handles Other References? | Performance |
---|---|---|---|
arr.length = 0 | ✅ Yes | ✅ Yes (updates all refs) | Fastest |
Reassignment (= [] ) | ❌ No (new array) | ❌ No (old refs remain) | Fast |
splice() | ✅ Yes | ✅ Yes | Fast |
Loop (pop /shift ) | ✅ Yes | ✅ Yes | Slow |
Example Scenarios
- If the array is declared with
const
:
const arr = [1, 2, 3];
arr.length = 0; // ✅ Works (mutates the array)
// arr = [] ❌ Throws an error (reassignment not allowed)
- Other references to the array:
let arr = [1, 2, 3];
let arr2 = arr; // arr2 references the same array
arr.length = 0; // Both arr and arr2 become []
Which Method Should You Use?
- Best for most cases:
arr.length = 0
(efficient and updates all references). - Avoid reassignment (
= []
) if other parts of your code reference the original array. - Avoid loops unless you need incremental processing.
Let me know if you need further clarification!