How do you clear an array in JavaScript?
Short answer: set its length to zero with arr.length = 0. It empties the array itself, works with const and every variable that points to that array sees it empty. If you only need a fresh empty array in one variable, arr = [] also works, but the old array keeps its items.
const fruits = ["apple", "banana", "cherry"];
fruits.length = 0;
console.log(fruits); // []There is no built-in clear() method for arrays. Set and Map have one, arrays don't.
length = 0 empties the array everywhere, = [] only gives one variable a new array, and a const can't be reassigned.
Every way to clear an array
| Method | Code | Changes the original array | Works with const | Returns |
|---|---|---|---|---|
| Set the length to 0 | arr.length = 0 | Yes | Yes | 0 |
splice() | arr.splice(0) | Yes | Yes | The removed items |
| Assign a new array | arr = [] | No, other references keep the items | No | [] |
pop() in a loop | while (arr.length) arr.pop() | Yes | Yes | Nothing, and it's slow |
For most code, arr.length = 0 is the clearest choice. Use splice(0) when you also want the items you removed.
Clear an array with length = 0
An array's length can be written. Setting it to 0 removes every item, and setting it to a smaller number keeps only the first ones:
const nums = [1, 2, 3, 4, 5];
nums.length = 2;
console.log(nums); // [1, 2]
nums.length = 0;
console.log(nums); // []Because it changes the array itself, it also empties arrays inside objects, like cart.items.length = 0.
