How to Check if an Array is Empty in JavaScript

Arrays are a common data structure in JavaScript because of how versatile and flexible they are.
With an array, you can add or remove items, and read its length to decide what to do further in your code.
However, sometimes it is important to be able to check if an array is empty or not.
In this post, we'll learn the best way to check if an array in JavaScript is empty.
How to check if an array is empty
Let's start out with two arrays, an empty one and a non-empty one.
const emptyArray = [];
const nonEmptyArray = [1, 2, 3];
Now we can use the .length
property to check if an array is empty or not because if it returns anything other than 0, it means it's not empty.
const emptyArray = [];
const nonEmptyArray = [1, 2, 3];
console.log(emptyArray.length);
console.log(nonEmptyArray.length);
0
3
Therefore, if you want to check if the array is empty or not, we can do a simple if
statement.
const emptyArray = [];
const nonEmptyArray = [1, 2, 3];
if (emptyArray.length === 0) {
console.log('The empty array is empty');
} else {
console.log('The empty array is not empty');
}
if (nonEmptyArray.length === 0) {
console.log('The non-empty array is empty');
} else {
console.log('The non-empty array is not empty');
}
The empty array is empty
The non-empty array is not empty
If you're not sure if the variable you are checking is a valid array or not, simply use the Array.isArray
function alongside your usual length checks:
const emptyArray = [];
const nonEmptyArray = [1, 2, 3];
if (Array.isArray(emptyArray) && emptyArray.length === 0) {
console.log('The empty array is empty');
} else {
console.log('The empty array is not empty');
}
if (Array.isArray(nonEmptyArray) && nonEmptyArray.length === 0) {
console.log('The non-empty array is empty');
} else {
console.log('The non-empty array is not empty');
}
The empty array is empty
The non-empty array is not empty
Conclusion
In this post, we've learned how to check if an array is empty or not, and how to ensure that variable we are checking is an array.
Simply use the .length
property to check if an array is empty or not, and use the Array.isArray
function to check if a variable is an array.
Thanks for reading this post!
If you want to learn about web development, founding a start-up, bootstrapping a SaaS, and more, follow me on X! You can also join the conversation over at our official Discord!
Leave us a message!