JavaScript: Check if an array is empty.

In this tutorial, we will show you how to check if a JavaScript array is empty or not. We will also check to see if the variable in question is the correct type.

For the purpose of this tutorial, we’ve created a custom JavaScript function called arrayIsEmpty.

Feel free to copy and paste it into your project if you’re looking for a quick and easy 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.
        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 will check to see if the array is empty. It will also make sure that the variable in question isn’t another type.

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 if 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 our function will presume that the array is empty and return a TRUE value.

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.