Clear an array using JavaScript

We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this blog, we look at the different methods to clear/empty an array using JavaScript.

Table of Contents

  • Substitution of an empty array
  • Assign array’s length to zero
  • Using the splice() method
  • Using the pop() method
  • Using the shift() method
  • Other Related Concepts

Substitution of an empty array

arry = [1, 2, 3, 4];
arry = [];

console.log(arry);
//Output: []

This method works as long as the array we want to clear has no references to it. Also, this method is the fastest & easiest way to clear an array.

Assign array’s length to zero

arry = [1, 2, 3, 4];
arry.length = 0;

console.log(arry);
//Output: []

When the length of an array is set to zero, all the array elements are automatically deleted.

Using the splice() method

The splice() method adds or removes elements to or from an array. It then returns the removed items.

Syntax:

array.splice(index, noOfElements, item1, ....., itemN)

Here,
  • Index: It is a required parameter that specifies the position to add or remove the elements from an array.
  • noOfElements: It is an optional parameter that indicates the number of elements to be removed from the specified Index
  • item1, ..., itemN: It is an optional parameter that specifies the new elements to be added at the specified index.

Example:

arry = [1, 2, 3, 4];
arry.splice(0,a.length);

console.log(arry);
//Output: []

The above example, removes all the elements of an array starting from zero essentially clearing the array.

The splice method returns all the removed elements from an array.


Using the pop() method

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

We can use this method inside a loop and iterate until the length of the array is greater than zero.

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

console.log(arry);
//Output: []

Using the shift() method

Similar to the pop() method, we could use the shift() method too. The only difference is that the shift() method removes the first element of the array instead of the last element like pop() method.

arry = [1, 2, 3, 4];
while (arry.length > 0) {
    arry.shift();
}

console.log(arry);
//Output: []

Overall, the pop() & shift() methods require a longer time & more number of lines of code as we remove elements one by one.