How to Empty a JavaScript Array
In JavaScript, there are multiple approaches to emptying an array. This blog post will discuss a couple of commonly used methods for clearing an array and emptying all its elements.
Method 1: Setting the Array Length
The easiest way to empty a JavaScript array is by setting its length to 0. This method works for both const
and let
declarations. Here’s an example:
1 | const list = ['a', 'b', 'c']; |
By changing the length of the array to 0, all its elements are automatically removed.
Method 2: Assigning an Empty Array
Alternatively, you can mutate the original array reference by assigning an empty array to the variable. However, this method requires using let
instead of const
. Here’s an example:
1 | let list = ['a', 'b', 'c']; |
In this case, the original array is replaced with an empty array, resulting in the removal of all its elements from memory.
Regardless of which method you choose, both effectively empty the array and remove all its elements.
tags: [“JavaScript”, “array”, “empty”, “clear”]