How to check if an array is empty using Javascript?

How to check if an array is empty using Javascript?

As a web developer, I have come across scenarios where I need to check if an array is empty or not using Javascript. There are multiple ways to achieve this, and I will discuss them below.

Method 1: Using the length property

The simplest way to check if an array is empty is by using the length property of the array. If the length of the array is 0, then it is empty. Here is an example code snippet:


    let myArray = [];
    if (myArray.length === 0) {
      console.log("Array is empty");
    }
  

Method 2: Using the Array.isArray() method

The Array.isArray() method returns true if the argument passed to it is an array. We can use this method along with the length property to check if an array is empty or not. Here is an example:


    let myArray = [];
    if (Array.isArray(myArray) && myArray.length === 0) {
      console.log("Array is empty");
    }
  

Method 3: Using the ! (not) operator

We can also use the ! (not) operator to check if an array is empty. If we apply the ! operator to an empty array, it will return true. Here is an example:


    let myArray = [];
    if (!myArray.length) {
      console.log("Array is empty");
    }
  

In conclusion, there are multiple ways to check if an array is empty using Javascript. You can choose any of the above methods based on your preference and coding style.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe