We can easily use JavaScript to check if an array is empty. An empty array has length 0, and is equal to False, so to check if an array is empty, we can just check one of these conditions.

var emptyArray = [];

#length check
if ( emptyArray.length == 0){
  console.log("Array is empty!");
}

#if statement check
if (!emptyArray.length) {
  console.log("Array is empty!");
}

In JavaScript, arrays are a collection of objects which are ordered. When working with arrays, it can be useful to be able to easily determine if the array is empty.

There are a few ways you can determine if an array is empty.

The length of an empty array will be 0. So we can use the length property to check for this. The length of an empty array will be equal to 0, or false, so we can also use this to determine if an array is empty.

In the following JavaScript code, you can see the two ways we can check if an array is empty or not.

var emptyArray = [];

#length check
if ( emptyArray.length == 0){
  console.log("Array is empty!");
}

#if statement check
if (!emptyArray.length) {
  console.log("Array is empty!");
}

Checking if an Array is Empty with an if Statement in JavaScript

One fact we can use in JavaScript to check if an array is empty is that an array that is empty is equivalent to the boolean value False.

In this case, we can test if an array is empty using a simple if statement.

var emptyArray = [];

#if statement check
if (!emptyArray.length) {
  console.log("Array is empty!");
}

Checking if an Array is Empty Using the JavaScript Length Property

One of the ways we can easily check if an array is empty in JavaScript is with the JavaScript length property.

The length of an array which is empty is 0.

Checking to see if an array is empty using the JavaScript length property is shown in the following JavaScript code.

var emptyArray = [];

if ( emptyArray.length == 0){
  console.log("Array is empty!");
}

Hopefully this article has been useful for you to learn how to use JavaScript to check if an array is empty.

Categorized in:

JavaScript,

Last Update: March 11, 2024