How Can I Determine If An Array Is Empty Or Non-existent In JavaScript?

There are several ways to check if an array is empty or does not exist in JavaScript.

  1. Using the length property:
    You can check if the length property of the array is equal to 0 to determine if it is empty. If the array does not exist, it will throw an error, so you can use the optional chaining operator (?.) to check if the array is null or undefined before accessing its length property.
if (arr?.length === 0) {
  console.log("Array is empty");
} else {
  console.log("Array is not empty");
}

Alternatively, you can use the Array.isArray() method to check if the variable is an array before checking its length property:

if (Array.isArray(arr) && arr.length === 0) {
  console.log("Array is empty");
} else {
  console.log("Array is not empty");
}
  1. Using the typeof operator:
    The typeof operator can be used to check if the array variable is undefined.
if (typeof arr === "undefined") {
  console.log("Array does not exist");
} else if (arr.length === 0) {
  console.log("Array is empty");
} else {
  console.log("Array is not empty");
}
  1. Using the Array.from() method:
    You can also utilize the Array.from() method to create an array from the original variable. If the original variable is undefined or null, an empty array will be returned. Then, you can check the length property.
if (Array.from(arr).length === 0) {
  console.log("Array is empty or does not exist");
} else {
  console.log("Array is not empty");
}

Note: It is important to handle the case of a non-existing array separately from an empty array, as they have different meanings.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!