JavaScript: Check if an array is empty.

This is a tutorial on how to check if a JavaScript array is empty or not. We will also check to see if the variable in question has actually been defined properly.

For the purpose of this tutorial, I’ve created a custom JavaScript function called arrayIsEmpty. Feel free to copy and paste it into your project if you’re just looking for a quick and lazy solution:

/**
 * JavaScript function that detects whether a JavaScript array
 * is empty.
 * 
 * @param array array
 * @returns {Boolean}
 */
function arrayIsEmpty(array){
    //If it's not an array, return TRUE.
    if(!Array.isArray(array)){
        return true;
    }
    //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;
}

The JavaScript function above checks to see if the array is empty or if it hasn’t been defined.

Firstly, it checks to see if the variable is an array by using the Array.isArray() method. If the variable in question is undefined or it is another variable type such as a string or an object, the function will return TRUE.

Once the function has confirmed that it is dealing with an actual array, it checks 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.

Finally, if it passes the two checks above, then our arrayIsEmpty function will return FALSE.

Take a look at the following example of the function in action:

//An example of a JavaScript that isn't empty.
var arrOne = new Array('BMW', 'Audi', 'Ford'); 

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

console.log(arrayIsEmpty(arrOne)); //returns FALSE
console.log(arrayIsEmpty(arrTwo)); //returns TRUE

As you can see, arrayIsEmpty returns FALSE for the first array, as it is definitely not empty. However, it returns TRUE for the second array.

And that’s it! As you can see, it’s actually pretty simple. All you have to do is make sure that the variable is an actual array and that its length property is equal to 0.

Related: How to check if a JavaScript object is empty.