How To Check Array Is Empty Or Null In Javascript

Websolutionstuff | Aug-18-2020 | Categories : PHP jQuery

In this example, I will show you how to check if an array is empty or null in javascript or jquery. When we are working in javascript and you want to loop the array at that time we need to check whether an array is empty or not. So, it doesn't return an error. There are many ways to check javascript array is empty or not.

So, let's see how to check if the array contains a value in jquery or jquery check if the value exists in an array of objects.

Using JQuery isEmptyObject()

 This method is reliable to check whether the 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>

 

Checking with the condition if an array is not undefined

Many times we are required to check that array should not be an undefined object and has at least one element. This can be also checked 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>

 

Checking by array length

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

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

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

 


You might also like:

Recommended Post
Featured Post
How to install TeamViewer in Ubuntu 22.04
How to install TeamViewer in U...

Hey there, Ubuntu users! If you've ever needed a hand troubleshooting your friend's computer from the comfort of...

Read More

Jan-17-2024

How To Create Validation Rule In Laravel 10
How To Create Validation Rule...

In this article, we will see how to create a validation rule in laravel 10. Here, we will learn about the laravel 1...

Read More

May-22-2023

How To Add Date Range Picker In Angular 15 Material
How To Add Date Range Picker I...

In this tutorial, I will guide you through the process of adding a date range picker component to your Angular 15 applic...

Read More

Jun-30-2023

Laravel 8 Autocomplete Search from Database
Laravel 8 Autocomplete Search...

In this article, we will see the laravel 8 autocomplete search from the database. Using ajax autocomplete...

Read More

Mar-01-2021