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 Svelte
How to Serve Static Files with Nginx and Docker
How to deploy a .NET app using Docker
How to deploy a PHP app using Docker
How to deploy a Deno app using Docker
How to deploy a MySQL Server using Docker
How to deploy a Node app using Docker
Using Puppeteer and Jest for End-to-End Testing
Getting Started with Moment.js
Learn how to build a Slack Bot using Node.js
Using Push.js to Display Web Browser Notifications
Getting Started with React
