Skip to content
the poor coder

How to check if an array is empty using Javascript?

Poor Man
Published
Reading time
1 min read
On this page

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:

Text

    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:

Text

    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:

Text

    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.

Keep going

2023

how to sort an array

How to Sort an Array If you have an array and you want to order its elements in a specific way, you need to use a sorting algorithm. There are several sorting algorithms available, but two of the most commonly used are…

javascript2 min read
2023

jquery mobile or desktop

jQuery Mobile or Desktop? As a web developer, I have had some experience with both jQuery Mobile and jQuery Desktop. Both frameworks have their pros and cons, and which one to use really depends on the specific project…

javascript1 min read
2023

node.js folder structure

Node.js Folder Structure If you are new to Node.js, it can be daunting to create a folder structure that will work for your project. The structure you choose will depend on the size and complexity of your project. Here…

javascript1 min read
ESC