4 Ways to Empty an Array in NodeJS
Introduction
There are various ways to empty an array of all it's contents. We'll show you each of the four ways in this article.
Let's get started!
Table of Contents
  1.  Create a New Empty Array
  2.  Set Length To Zero
  3.  Using Splice()
  4.  Loop Over & Remove Each Value
1. Create a New Empty Array
This method will create a brand new array and is the fastest method of the four because it doesn't change anything in the original array.
Here's the code:
Node.js
 
let names = ["Johnny", "Billy", "Sandy"]
 
names = []
// []
You should be careful with this method because if you've referenced the original array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original value.
2. Set Length To Zero
This method uses the .length method to set the length of the array to zero.
This is the second-fastest method of the four.
Here's the code:
Node.js
 
const names = ["Johnny", "Billy", "Sandy"]
 
names.length = 0
// []
3. Using Splice()
This method uses the splice() method to return the array with all the removed items.
Here's the code:
Node.js
 
const names = ["Johnny", "Billy", "Sandy"]
 
names.splice(0, names.length)
// []
This method will return a copy of the original array. But it doesn't have much of an effect on performance.
4. Loop Over & Remove Each Value
This method will use a while loop to pop() each item in the array. This is both the slowest and least succinct method of the four.
Here's the code:
Node.js
 
const names = ["Johnny", "Billy", "Sandy"]
 
while (names.length > 0) {
  names.pop()
}
// []
Conclusion
There you have it! These are four ways to empty an array in Node.js.
Did we miss any methods you know of? Let us know in the comments!
As always, thanks for reading!