This post will discuss how to clear an array in JavaScript.

1. Using [] operator

The simplest solution is to set the variable holding the array to a new empty array using an array constructor or literal notation. This works fine if we don’t have any other references to the original array. Still, it doesn’t clear any existing references to the original array since the original array remains unchanged.

The following code example demonstrates this behavior:

Download  Run Code

2. Using Array.length

To update any existing references to the array, consider changing the length property of the array. The following program sets the length property of an array to 0, which completely truncates it.

Download  Run Code

3. Using Array.prototype.splice() function

The splice() method is frequently used in JavaScript for removing existing elements from the array in-place. The following code example demonstrates the usage of the splice() method to empty the content of the array.

Download  Run Code

That’s all about clearing an array in JavaScript.