How to Check if an Array is Empty in JavaScript
Table of Contents
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.
JAVASCRIPTconst 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.
JAVASCRIPTconst emptyArray = [];
const nonEmptyArray = [1, 2, 3];
console.log(emptyArray.length);
console.log(nonEmptyArray.length);
BASH0
3
Therefore, if you want to check if the array is empty or not, we can do a simple if
statement.
JAVASCRIPTconst 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');
}
BASHThe 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:
JAVASCRIPTconst 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');
}
BASHThe 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!
- Getting Started with TypeScript
- Managing PHP Dependencies with Composer
- Git Tutorial: Learn how to use Version Control
- How to build a Discord bot using TypeScript
- How to deploy a PHP app using Docker
- How to deploy a Node app using Docker
- Getting Started with Sass
- Creating a Twitter bot with Node.js
- Getting Started with React
- Getting Started with Vuex: Managing State in Vue
- Using Axios to Pull Data from a REST API
- Getting Started with Moon.js