When working with arrays in JavaScript, it’s common to need a quick way to check if the array contains any elements. This is especially useful when processing data fetched from an API, form inputs, or user selections.

What is an Array in JavaScript?

An array in JavaScript is a special type of object used to store multiple values in a single variable. Each value (or element) has a numeric index.

const fruits = ["Apple", "Banana", "Cherry"];

How to Check if an Array is Empty?

To check if a JavaScript array is empty, you simply check its .length property. The .length property returns the number of elements in the array.

Syntax:

array.length === 0

Example:

const items = [];
if (items.length === 0) {
 console.log("The array is empty.");
} else {
 console.log("The array is NOT empty.");
}

Output:
The array is empty.

Creating a Reusable Function

function isArrayEmpty(arr) {
 return Array.isArray(arr) && arr.length === 0;
}
// Usage
console.log(isArrayEmpty([]));          // true
console.log(isArrayEmpty([1, 2, 3]));   // false
console.log(isArrayEmpty("Not array")); // false

Using Array.isArray() ensures the input is actually an array, avoiding errors if the input is something else like null or undefined.

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