DEV Community

tutorials-kept-simple
tutorials-kept-simple

Posted on • Originally published at flexiple.com

How to check if an array is empty using Javascript?

We continue with Flexiple's tutorial series to explain the code and concept behind common use cases. In this article, we will solve for a specific case: To check if an array is empty using Javascript.

Where can we use this?

You might find this useful when you want to execute a particular script if the array is empty - like enabling or disabling buttons based on if there is any input in the required field, etc.

If you are new to programming or quite unfamiliar with javascript, we recommend you read through the entire article, as each section of the article would be useful.

However, if you are just looking for the code, you can quickly check out the section below.

Table of Contents

Code to check if an array is empty using javascript

We will quickly go over the code and its demonstration to check if an array is empty or not and also see why these specific functions are used.

//To check if an array is empty using javascript
function arrayIsEmpty(array){
    //If it's not an array, return FALSE.
    if(!Array.isArray(array)){
        return FALSE;
    }
    //If it is an array, check its length property
    if(array.length == 0){
        //Return TRUE if the array is empty
        return true;
    }
    //Otherwise, return FALSE.
    return false;
}
Enter fullscreen mode Exit fullscreen mode

Code Explanation

Let's breakdown this code step by step!

  • First we check if a variable is an array using the Array.isArray() method.
  • If the variable passed is an array then the condition !Array.isArray() will be False and so the variable will go to the else condition.
  • If the variable passed is anything but an array such as, undefined or another variable type such as a string or object, the function will return False.
  • Having confirmed that the variable is an array, now we can check the length of the array using the Array.length property.
  • If the length of the object is 0, then the array is considered to be empty and the function will return TRUE.
  • Else the array is not empty and the function will return False.

Demonstration of checking if the array is empty using Javascript

var fruitArr = new Array('Apple', 'Mango', 'Grapes');

//An example of a JavaScript array that is empty.
var arrTwo = new Array();

console.log(arrayIsEmpty(fruitArr)); //returns FALSE
console.log(arrayIsEmpty(arrTwo)); //returns TRUE
Enter fullscreen mode Exit fullscreen mode

Output

FALSE
TRUE
Enter fullscreen mode Exit fullscreen mode

Output Explanation

  • We can see here that fruitArr is an array and hence passes into the second condition to check if the length of the array is empty.
  • Since the array has 3 elements it is not empty and therefore the function returns False.
  • In the second case, arrTwo, it is again an array and so passes into the second condition.
  • Here, since the array is empty, the function returns True.

Why use the Array.isArray() method?

The Array.isArray() method is a sure shot method to check if a variable is an array or not and it automatically eliminates the cases of null and undefined without writing an additional script to check for it.

The Array.isArray() method returns true for the following cases

Array.isArray([]);
Array.isArray([3]);
Array.isArray(new Array());
Array.isArray(new Array('apple', 'mango', 'grapes'));
Array.isArray(new Array(5));
Array.isArray(Array.prototype);
Enter fullscreen mode Exit fullscreen mode

Note: Array.prototype itself is an array so the function Array.isArray() returns TRUE.

The Array.isArray() returns False for the following cases

Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(21);
Array.isArray('Random String');
Array.isArray(true);
Array.isArray(false);
Array.isArray(new Uint8Array(32));
Array.isArray({ __proto__: Array.prototype });
Enter fullscreen mode Exit fullscreen mode

Can we use typeof instead of the Array.isArray?

The answer is NO, because an array in JavaScript is an instance of the Array object and typeof would return the type object for it.

To illustrate this, consider for example:

const array = ['a', 'b', 'c'];

console.log(typeof array);   // output: 'object'

console.log(array instanceof Array); // output: true
Enter fullscreen mode Exit fullscreen mode

Can we use instanceof instead of Array.isArray?

While instanceof can be used for most cases in place Array.isArray , the Array.isArray is preferred over instanceof as it works through multiple contexts (such as frames or windows) correctly whereas instanceof does not.

The reason for this is that in javascript each window or frame has its own execution environment, thus having a different scope from each other. This means that they have different built-in objects (i.e. different global objects, different constructors, etc.). This may lead to unexpected results when using instanceof, for example, for scripts passing objects from one context to another via functions.

Considering such cases, it is best to simply use Array.isArray, especially when creating a framework, library, or a plugin, where the environment in which it will be used is not known in advance.

Using the length property

Once we have made sure we are dealing only with an array, we can easily check if the array is empty or not using the length property. If the length of the array is 0, then the array is empty otherwise it is not empty.

One obvious question we might have is why not just use the length property at the beginning itself? Won't it make the code simpler?

True, but length property can return that the variable is empty even for non-array variables so we need to ensure that we are dealing with an array first before using the length property.

Browser Support

The Array.isArray method has very good browser support as it is part of the ES5 specification. However, if the browsers you're targeting lack the support, you can use a polyfill for it which is given below.

The polyfill works well with browsers that are compatible with ES3 specifications and works across frames.

if (!Array.isArray) {
    Array.isArray = function(arg) {
        return Object.prototype.toString.call(arg) === '[object Array]';
    };
}
Enter fullscreen mode Exit fullscreen mode

Top comments (3)

Collapse
 
jonrandy profile image
Jon Randy 🎖️ • Edited

Why so long?

const isEmptyArray = a=>Array.isArray(a) && !a.length
Enter fullscreen mode Exit fullscreen mode

Checking it is an Array is also not necessary, so you can just do:

const isEmptyArray = a=>!a.length
Enter fullscreen mode Exit fullscreen mode
Collapse
 
pixodev profile image
PixoDev • Edited

I’ve been using if(!array.length) during my whole carrier, which benefits does your util have over it?

Collapse
 
jonrandy profile image
Jon Randy 🎖️

None