To make an already existing array empty in JavaScript, you can use several methods to remove all elements from the array:

Setting Length to 0:

You can set the length property of the array to 0. This method truncates the array, effectively removing all its elements:

let arr = [1, 2, 3];
arr.length = 0; // Makes the 'arr' array empty

Using splice():

You can use the splice() method to remove all elements from the array starting from index 0:

let arr = [1, 2, 3];
arr.splice(0, arr.length); // Removes all elements from 'arr'

Using pop() in a Loop:

You can repeatedly use the pop() method in a loop to remove elements until the array becomes empty:

let arr = [1, 2, 3];
while (arr.length > 0) {
 arr.pop();
}

Assigning a New Empty Array:

You can assign a new empty array [] to the existing array variable. This reassigns the variable to reference a new empty array, effectively emptying the original array:

let arr = [1, 2, 3];
arr = []; // Assigns 'arr' to a new empty array, making the original array empty

Need Help With Javascript Development?

Work with our skilled Javascript developers to accelerate your project and boost its performance.

Hire JavaScript Developers

Support On Demand!

Related Q&A