How to Empty an Array in JavaScript

There are four ways to empty(clear) an array in JavaScript : 

  • Method 1: Assign an array to an empty array
  • Method 2: Setting an array length to 0
  • Method 3: Using the splice() method
  • Method 4: Using pop() in a Loop

Method 1: Assigning an array to an empty array

If you don’t need to maintain references to the original array, you can simply assign a new empty array to the variable

Visual Representation

Visual Representation of Assigning an array to an empty array

Example

let x = [10, 20, 30, 40, 50]
console.log(x)

x = []
console.log("Empty array: ", x)

Output

[ 10, 20, 30, 40, 50 ]
Empty array: []

Method 2: Setting an array length to 0

Setting it to 0 means we are emptying the array. All the elements will be cleared automatically. This method is effective and fast.

Visual Representation 

Visual Representation of Setting an array length to 0

Example

let x = [10, 20, 30, 40, 50]
console.log(x)

x.length = 0;
console.log("Empty array: ", x)

Output

[ 10, 20, 30, 40, 50 ]
Empty array: []

Method 3: Using the splice() function

The splice() method can also be used to clear an array.

Visual Representation

Visual Representation of Using the splice() function

 

Example

let x = [10, 20, 30, 40, 50]
console.log(x)

x.splice(0, x.length)
console.log("Empty array: ", x)

Output

[ 10, 20, 30, 40, 50 ]
Empty array: []

Method 4: Using pop() in a Loop

While less efficient, you can also empty an array by repeatedly calling pop() until the array is empty.

Visual RepresentationVisual Representation of Using pop() in a Loop

Example

let x = [10, 20, 30, 40, 50]

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

console.log("Empty array: ", x)

Output

Empty array: []

This solution can cause a performance issue.

Overall, The most common and efficient way is setting the length to zero.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.