How to empty a JavaScript array
By Flavio Copes
Learn how to empty a JavaScript array, either by setting its length to 0 to clear it in place or by reassigning the variable to a new empty array with let.
To empty a JavaScript array you can set its length to 0, which removes all the items in place:
const list = ['a', 'b', 'c']
list.length = 0
console.log(list) //[]
This works because length is a writable property. When you set it to a number smaller than the current length, JavaScript drops every item past that point. Setting it to 0 drops everything.
Notice this works with const. We’re not reassigning the variable, we’re mutating the array it points to.
Assigning a new empty array
Another approach is to assign an empty array to the variable. This requires let instead of const:
let list = ['a', 'b', 'c']
list = []
This does not empty the original array. It creates a brand new empty array, and points the variable to it. The old array is still there in memory, untouched. That distinction matters, and it’s where a common bug hides.
The pitfall: other references
Suppose two variables point to the same array:
let cart = ['bread', 'milk']
const backup = cart
cart = []
console.log(backup) //[ 'bread', 'milk' ]
cart is now empty, but backup still holds the old items. Any other part of your code that kept a reference to the array keeps seeing the old content, because reassigning cart only changed what that one variable points to.
Setting the length to 0 avoids this, because it empties the array in place:
const cart = ['bread', 'milk']
const backup = cart
cart.length = 0
console.log(backup) //[]
Both variables point to the same array, and that array is now empty.
Another option: splice()
splice() can also empty the array in place:
const list = ['a', 'b', 'c']
const removed = list.splice(0)
console.log(list) //[]
console.log(removed) //[ 'a', 'b', 'c' ]
Called with 0 as the starting index and no end, it removes every item. It also returns the removed items, which is handy if you want to do something with them before discarding.
Which one should you use?
My advice: use list.length = 0 (or splice()) when other code might hold a reference to the same array. Use list = [] when you know the variable is the only reference. The reassignment reads more clearly, but emptying in place is the safer default when the array is shared.
Related posts about js: