To check if an array is empty or doesn’t exist in JavaScript, you can use a simple conditional check.

Foolproof Method

The most reliable way to check is to first verify if the variable is an array and then check its length. This prevents errors if the variable is not an array.

JavaScript
if (!Array.isArray(array) || !array.length) {
  // array does not exist, is not an array, or is empty
}

Pragmatic Method

A shorter, more common approach is to check if the array or its length is “falsy” (e.g., null, undefined, or 0).

JavaScript
JavaScript
if (!array || !array.length) {
  // array is falsy or its length is 0
}

Modern Approach (Optional Chaining)

With modern JavaScript (ES2020 and later), you can use the optional chaining operator (?.) to make the check even more concise. This is a very clean and readable way to handle this situation.

JavaScript
if (!array?.length) {
  // array is falsy or its length is 0
}

Need Help With Javascript Development?

Work with our skilled Javascript developers to accelerate your project and boost its performance.

Hire JavaScript Developers

Support On Demand!

Related Q&A