Empty an array in JavaScript

In this tutorial, we will learn how to empty an array in JavaScript.

To make it clear and understandable, I will simply take an array variable and put some elements in it. Then I will show multiple ways to empty that array.

We can clear or empty the contents of an array to do this. This means removing all the elements from an array.

We can make an array empty by following methods and techniques

  • Setting Array Length to 0
  • Using the splice() Method
  • Reassigning the Array

Now, I am going to explore the above-mentioned methods and techniques one by one to make an array empty.

Setting Array Length to 0

I have taken an array variable Array.  Now just set its length to zero by using this: Array.length = 0.

As I have set the length to zero that means this variable can’t hold any element in it, thus it will be empty.

Example

let Array = [3, 5, 9, 8]

// To clear or empty the array
Array.length = 0
console.log(Array)

Output:

[]

Using the splice() Method

Here I have used the splice() method to remove all elements from an array starting from index 0. This method modifies the original array in place.

It’s always better to take an example:

Example

let Array = [3, 5, 9, 8]

// To clear or empty the array
Array.splice(0)
console.log(Array)

Output:

[]

Reassigning the Array

We can simply reassign the array variable to a new empty array using the assignment operator =. This effectively removes all elements from the original array and creates a new empty array in its place.

Example

let Array = [3, 5, 9, 8]

// To Reassign the 'Array' variable to an empty array
Array = [];
console.log(Array)

Output:

[]

Leave a Reply

Your email address will not be published. Required fields are marked *