Check if array is empty or null in Javascript

When working in Javascript, many times you need to check if array is empty or undefined. This needs to check when you want to loop the array, so it doesn't return error.

There are lot of ways to check if Javascript array is empty or not. Here are some examples:

Checking by array length

The first way to check is to get array length. If the array length is 0, then it empty array.

<script type="text/javascript">
    var newArray = [1];

    if (newArray && newArray.length > 0) {
        // newArray is not empty
    } else {
        // newArray is empty
    }
</script>

Checking if array is not undefined

Sometimes you also want to check that array should not be undefined object and has at least one element. This can be also check with typeof.

<script type="text/javascript"> 
    var undefinedAray = undefined;

    if (typeof undefinedAray !== "undefined" && undefinedAray.length > 0) {
        // undefinedAray is not empty
    } else {
        // undefinedAray is empty or undefined
    }
</script>

Using JQuery isEmptyObject() method

We can also use JQuery isEmptyObject method to check whether array is empty or contains elements. This is reliable method.

<script src="https://code.jquery.com/jquery-3.5.0.min.js"></script>
<script type="text/javascript">
    var newArray1 = [1, 2, 3];
    var newArray2 = [];

    console.log(jQuery.isEmptyObject(newArray1)); // returns false
    console.log(jQuery.isEmptyObject(newArray2)); // returns true
</script>

This way you can check wether array contains element or is empty. I hope this article will help you a little.

 
 
 
 
Tags: