βοΈ How to Check if an Array is Empty in JavaScript? π π
3 min read 6 days ago
Method 1: Using the length
Property
The simplest and most common way to check if an array is empty is by using the length
property. The length
property returns the number of elements in the array. If the length is zero, the array is empty.
Not a Member Click here to read free
Example:
let arr = [];
if (arr.length === 0) {
console.log("The array is empty.");
} else {
console.log("The array is not empty.");
}
Explanation:
- In this example, the array
arr
is initialized as an empty array ([]
). - The
if
statement checks if the length of the array is zero. If true, it logs "The array is empty"; otherwise, it logs "The array is not empty."
Method 2: Using Array.isArray()
and length
Before checking if an array is empty, itβs good practice to ensure the variable is actually an array. The Array.isArray()
method can be used in combination with the length
property to perform this check.