Check if an Array is Empty in JavaScript

Check if an Array is Empty in JavaScript

To check if an array is empty in JavaScript, you can use the Array.prototype.length property, which returns the number of elements in the array. If the length is 0, then the array is empty. Here's an example:

Check if an Array is Empty Examples

Check using the length method

const array = ['apple', 'banana', 'orange'];

if (array.length === 0) {
  console.log('The array is empty');
} else {
  console.log('The array is not empty');
}

In this example, we are checking if the array has any elements. If the length property is equal to 0, then we know that the array is empty. Otherwise, we know that it is not empty.

Here's an example of the output you might see from this code:

The array is not empty

This indicates that the array contains at least one element, so it is not empty.

Check using Array.prototype.every() Method

Another way to check if an array is empty is to use the Array.prototype.every() method, like this:

const array = ['apple', 'banana', 'orange'];

if (array.every(value => value === null)) {
  console.log('The array is empty');
} else {
  console.log('The array is not empty');
}

In this example, we are using the every() method to check if every value in the array is null. If this is the case, then the array is empty. Otherwise, it is not empty.

The output of this code would be the same as the previous example:

The array is not empty

Which indicates that the array is not empty because it contains non-null values.

The above post provides examples and output for checking if an array is empty in JavaScript. It explains two different approaches for checking if an array has no elements, using the length property and the every() method.

Related:

  1. Empty All Elements of Array in JavaScript