This post will discuss how to delete all elements from an array in JavaScript.

There are several ways to delete all elements from an array in JavaScript. Here are some examples of how to delete all elements from an array in JavaScript given an array:

1. Using length property

The length property reflects the number of elements in an array. We can use it to delete all elements from an array by setting it to zero. This is a simple and efficient way to empty an array in JavaScript. For example, if we have an array [1, 2, 3, 4, 5] and we want to delete all elements, we can do:

Download  Run Code

2. Using splice() function

The Array.splice() function changes the contents of an array by removing existing elements and/or adding new elements. We can pass a start index of zero and a delete count equal to the length of the array. This will delete all elements from the array and return a new array containing the removed elements. For example, if we have an array [1, 2, 3, 4, 5] and we want to delete all elements, we can do:

Download  Run Code

3. Using array literal

We can use array literal to create a new empty array and assign it to the variable that holds the original array. This way, we can delete all elements from an array without modifying it. However, any existing references to the original array will not be discarded. The following code illustrates this:

Download  Run Code

That’s all about deleting all elements from an array in JavaScript.