empty array in javascript

How to Empty Array in JavaScript

JavaScript arrays are powerful data structures that is used by many web developers and organizations. They offer many features and functions. Often you may need to clear an existing JS array. This is not a problem if the array has only a few elements. But if there are many elements in your array or each element of your array has a lot of data then it can be time consuming to empty it, depending on the method you employ for this purpose. In this article, we will learn how to empty array in JavaScript.


How to Empty Array in JavaScript

Here are the different ways to empty array in JavaScript. Let us say you have the following array in JavaScript.

var a = [1, 2, 3, 4, 5]

1. Reassign Array

In this method we simply reassign the array to an empty array.

a = []

This is a great way to empty an array if you have not referenced it by another variable. However if you have referenced it, then the original array remains unchanged.

b = a;
a = [];
console.log(b); //[1, 2, 3, 4, 5]

2. Set Array Length to 0

Another easy way to empty an array is to set its length to 0.

a.length = 0;

This method works in all implementations of JavaScript, including strict mode.

3. By Splicing Array

You can also empty an array by splicing it. Every array supports splice() function that allows you to remove or replace existing elements and add new elements. You can also use it to empty an array as shown below.

a.splice(0,a.length)

The first argument of splice() function is meant for index where items are to be added/removed. Next argument specifies the number of elements to be removed. So we are effectively saying that we need to remove a.length number of elements starting from position 0. In other words, this will empty the array and return a copy of the original array.

4. Popping Array Items

You can loop through the array items one by one and pop the elements one by one till it is empty.

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

In this article, we have seen several ways to clear an array. Of all these methods, #2 and #3 are the fastest while #4 is the slowest. So you can use any of these methods depending on your requirement. Of course, there are plenty of other ways to empty an array in JavaScript but we have looked at some of the simple ones.

Also read:

How to Set Query Timeout in MySQL
How to Count Frequency of Array Items in JavaScript
How to Allow Only Alphabet Input in HTML Text Input
How to Allow Only Numeric Input in HTML Text Input
How to Disable Scrolling in HTML/JavaScript

Leave a Reply

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