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
- Create an RSS Reader in Node
- Getting Started with Electron
- Git Tutorial: Learn how to use Version Control
- Best Visual Studio Code Extensions for 2022
- How to build a Discord bot using TypeScript
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Getting User Location using JavaScript's Geolocation API
- Learn how to build a Slack Bot using Node.js
- Getting Started with React
- Setting Up Stylus CSS Preprocessor