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:

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:

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.

Facebook Comments