How To Empty An Array In JavaScript

To empty an array in JavaScript, you can use any of these methods –

  1. Use arr = [] to empty an array.
  2. Use arr.length = 0 to empty an array.
  3. Use splice() method to remove all elements from an array.
  4. Use arr.pop() method inside a for loop

Let’s discuss each of these methods in detail below.

how to empty an array in javascript

1) Use arr = [] To Empty An Array In JavaScript

This is the most commonly used method to empty an array.

You simply assign a new empty array to the existing array variable.

For example, consider the following array −

var arr = ['a', 'b', 'c', 'd'];

Now, to empty this array, you can use the assignment operator as follows −

arr = []; //empty arr

This will set the value of arr to a new empty array.

You can verify it using the typeof operator as follows −

console.log(typeof arr); //returns 'object'

console.log(arr); //[]

2) Use arr.length = 0 To Empty An Array In JavaScript

This is another popular way to empty an array.

You simply set the length property of the array to zero.

For example, consider the following array −

var arr = ['a', 'b', 'c', 'd'];

Now, to empty this array, you can use the assignment operator as follows −

arr.length = 0; //empty arr

This will set the value of arr to a new empty array.

You can verify it using the typeof operator as follows −

console.log(typeof arr); //returns 'object'

console.log(arr); //[]

3) Use splice() Method To Remove All Elements From An Array

The splice() method is used to delete and/or insert new elements into an array.

The first parameter of this method is the index position of where you want to start deleting elements.

For our example, we will start deleting elements from index position 0.

The second parameter is the number of elements you want to delete.

For our example, we will delete all the elements in the array, so we will use arr.length for this parameter.

Therefore, to empty an array using splice(), you can do as follows −

var arr = ['a', 'b', 'c', 'd'];

arr.splice(0, arr.length);

console.log(typeof arr); //returns 'object'

console.log(arr); //[]

5) Use arr.pop() Method Inside A while Loop

You can also use the pop() method inside a while loop to empty an array.

The pop() method removes the last element of an array, and returns that element.

Therefore, if you keep on popping elements from an array, eventually the array will be emptied as follows −

var arr = ['a', 'b', 'c', 'd'];

while(arr.length> 0) {

arr.pop();

}

console.log(typeof arr); //returns 'object'

console.log(arr); //[]

As you can see from the above examples, using any of the above methods will successfully empty an array in JavaScript.

So choose the method that best suits your needs and use it in your code accordingly.

Leave a Reply