Javascript

How to Check if a JavaScript Array is Empty or Not? Examples Included

Javascript

How to Check if a JavaScript Array is Empty or Not? Examples Included

In JavaScript, you often need to check whether an array is empty or contains elements before performing certain operations. An empty array signifies that it has no elements, while a non-empty array has one or more elements. In this post, we'll explore different methods to check if a JavaScript array is empty or not, along with practical examples.

Method 1: Using length Property

The simplest way to check if an array is empty is by using the length property. An array with no elements has a length of 0, so you can use this property to determine if the array is empty.

// Example 1
const array1 = [];
if (array1.length === 0) {
  console.log("Array is empty.");
} else {
  console.log("Array is not empty.");
}

// Output: Array is empty.
// Example 2
const array2 = [1, 2, 3];
if (array2.length === 0) {
  console.log("Array is empty.");
} else {
  console.log("Array is not empty.");
}

// Output: Array is not empty.

Method 2: Using Array.isArray() and length Property

You can also combine the Array.isArray() method with the length property to check if the variable is an array and if it's empty or not.

// Example 3
const array3 = [];
if (Array.isArray(array3) && array3.length === 0) {
  console.log("Array is empty.");
} else {
  console.log("Array is not empty.");
}

// Output: Array is empty.
// Example 4
const array4 = "not an array";
if (Array.isArray(array4) && array4.length === 0) {
  console.log("Array is empty.");
} else {
  console.log("Array is not empty.");
}

// Output: Array is not empty.

Method 3: Using ! Operator

You can use the ! operator to check if the array is empty. By converting the array to a Boolean value with the ! operator, you can determine if it is falsy (empty) or truthy (non-empty).

// Example 5
const array5 = [];
if (!array5.length) {
  console.log("Array is empty.");
} else {
  console.log("Array is not empty.");
}

// Output: Array is empty.
// Example 6
const array6 = [1, 2, 3];
if (!array6.length) {
  console.log("Array is empty.");
} else {
  console.log("Array is not empty.");
}

// Output: Array is not empty.

Conclusion

Checking if a JavaScript array is empty or not is a common operation in many applications. You can use the length property, the Array.isArray() method, and the ! operator to determine whether an array contains elements or not. By using these methods, you can efficiently handle arrays in your JavaScript code and implement the necessary logic based on their contents.