4 Ways to Empty an Array in JavaScript

There are the following ways to empty an array in JavaScript.

Method 1: Set the array’s length to 0

By setting the “length of an array to 0”, you effectively remove all its elements. This approach is fast and works with the original array reference.

Example

const arr = [1, 2, 3, 4, 5];
arr.length = 0;

console.log(arr);

Output

[]

Method 2: Using the splice() function

The “splice()” function removes elements from an array. By calling splice(0) with the starting index as 0, you remove all elements from the array. This method also works with the original array reference.

Example

const arr = [1, 2, 3, 4, 5];
arr.splice(0);

console.log(arr);

Output

[]

Method 3: Assign an empty array literal

By assigning an “empty array literal ([])” to the “variable”, you create a new empty array. However, this method does not empty the original array reference, and any other references to the original array will remain unchanged.

Example

let arr = [1, 2, 3, 4, 5];
let originalArr = arr;

arr = [];

console.log(arr);
console.log(originalArr); 

Output

[]
[ 1, 2, 3, 4, 5 ]

Method 4: Using a while loop to remove elements

You can also use a while loop to remove elements one by one from the array. This method can be slower than the other methods but works with the original array reference.

Example

let arr = [1, 2, 3, 4, 5];

while (arr.length > 0) {
  arr.pop();
}

console.log(arr);

Output

[]

In this code example, we used a while loop to repeatedly call the pop() method, which removes the last element from the array until the array is empty. Unfortunately, this is not cost-effective, and I recommend you not use it.

Leave a Comment