How to Empty an Array in JavaScript
Sometimes, you want to empty an array instead of adding one. However, there are multiple ways of clearing an array which we are going to discuss in this tutorial to make it much easier for you.
Let's assume we have an array, and we want to clear it.
The first method can be the following:
let arr = [];
Running the code above will set the arr to a new clean array. This is good if you don't have references to the original array.
use this method if you only reference the array by its original variable arr. The original array will remain unchanged if you have referenced this array from another variable or property.
Here is an issue example you may encounter:
Another method you can encounter is setting the length of the array to 0.
arr.length = 0;
The third method is using .splice(), which will work fine. However, it will return a copy of the original array as the function returns an array with all the removed items.
arr.splice(0, A.length)
All the methods mentioned above are similar and can be used to clear the existing array, but the fastest ones are the second and third methods.
Arrays
Arrays are used to store several values in one variable. Neither the length of an array nor the types of its elements are fixed. Whenever you change the array, the length property automatically updates. It's not the count of values in the array, but the numeric index + 1. The length property is writable. When you decrease it, the array will be truncated.