How To Check Array Is Empty Or Null In Javascript

In this example, I will demonstrate how to determine if an array is empty or null in JavaScript or jQuery. When working in JavaScript, it's crucial to verify whether an array is empty, especially when you plan to loop through its elements.

You can accomplish this by checking the array's length property, which indicates the number of elements within it. An empty array will have 0 elements, and checking its length won't result in an error.

There are several methods available in JavaScript to check if an array is empty or not, including:

  1. isEmptyObject
  2. Using the length property.

Explore various techniques for checking if an array is empty or null in JavaScript or jQuery. When working with JavaScript, it's essential to ensure your arrays are empty before looping through them. Discover the built-in functions and the length property to effectively determine whether an array contains elements or is empty.

Using JQuery isEmptyObject()

This method is a reliable way to determine whether the array is empty or contains elements.

<script src=""></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


Checking with the condition if an array is not undefined

Often, we need to ensure that an array is neither an undefined object nor empty, and you can achieve this using the 'typeof' operator.

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

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



Checking by array length

You can check an array using its length property; if the array's length is 0, it indicates that the array is empty.

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

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



In conclusion, we have explored various methods to determine whether an array is empty or contains elements in JavaScript and jQuery. Ensuring that an array is defined and has at least one element is a common requirement in many programming scenarios.

By using techniques like checking the array's length property or utilizing the 'typeof' operator, we can reliably achieve this validation. These methods empower us to write more robust and error-resistant code when working with arrays, enhancing the reliability of our JavaScript and jQuery applications.


You might also like:


Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.