DEV Community

loading...

How To Check Array Is Empty Or Null In JavaScript

websolutionstuff profile image Websolutionstuff Originally published at websolutionstuff.com ・1 min read

In this example i will show you how to check array is empty or null in JavaScript or jQuery. When we are working in java script and you want to loop the array that time we need to check whether array is empty or not, so it doesn't return error.

There are many ways to check Java script array is empty or not so I will give you some examples.

Using JQuery isEmptyObject()

This method is reliable to check whether array is empty or contains elements.

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

    console.log(jQuery.isEmptyObject(Array1)); // returns false
    console.log(jQuery.isEmptyObject(Array2)); // returns true
</script>
Enter fullscreen mode Exit fullscreen mode

Checking with condition if array is not undefined

Many times we required 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>
Enter fullscreen mode Exit fullscreen mode

Checking by array length

We can check array with length, if array length is 0 then array is empty.

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

    if (Arraylegnth && Arraylegnth.length > 0) {
        // Arraylegnth is not empty
    } else {
        // Arraylegnth is empty
    }
</script>
Enter fullscreen mode Exit fullscreen mode

So, I have used 3 different method to check whether array is empty or not in JavaScript.

Read Also : Crop Image Before Upload Using Croppie Plugin

Discussion (0)

pic
Editor guide