How do I empty an array in JavaScript?
Simply set the length
property of the array to 0:
You can also preserve references to the original array, by using the splice method:
Different Clearing Methods Explained
When you need to keep references
In JavaScript, you might have multiple references
pointing to the same array. When you clear an array and still want to preserve these references, you should use:
This works the same with the splice()
method too:
When it's okay to break references
If it's not important for you to maintain the same array reference, re-assign an empty array. But remember, this kind of approach leaves previous references with the old array:
Extraction of The Flash: Speed comparison
Different array clearing methods have different performance. To help you decide which one suits best for your code, here's a brief comparison:
length: 0
andsplice()
are quick as lightning and preserve references.[]
might have same speed, but creates a whole new array, making your previous references confused.pop()
inside a loop is like a snail on the racetrack - slow and doesn't always finish the job properly because of falsy values.
Element removal: The tortoise race
A while-loop with pop()
does the job, but it's not as efficient:
Note the tricky part with this approach. This might prematurely brake the loop if an element is falsy:
Emptied, not replaced
Now consider this scenario: a special train that can simply vaporize its passengers, while being the same train:
A wish-list feature
We all know that JavaScript continues to evolve. In an ideal world, we would have a method like Array.clear()
, but alas, we need to create our own:
BenchPress for your Code
Performance can be a concern when running heavy-duty arrays. Use performance benchmark tools such as jsben.ch
and see which method raids the CPU less. And remember, comparison between arrays using ==
will prove unsuccessful, as they aren't the same object.
Cross-browser compatibility and future-proofing
Evergreen In all browsers
The good news is both length: 0
and splice()
have cross-browser compatibility:
Choose your Cleaner
Think of clearing an array as deciding on a cleaning service for your room. It can be quick and thorough (length: 0
), keeping the room intact yet sparkling. Or it can opt for complete makeover (A = []
).
Factors affecting your choice
Select the best method for your array depending on:
- Efficiency: How fast it needs to finish?
- Referential integrity: Should other variables be enlightened with the emptied array?
- Browser compatibility: Can it run even on your great-grandpa's browser?
Was this article helpful?