How to Check if an Array is Empty in JavaScript

Updated onbyAlan Morel
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.

JAVASCRIPT
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.

JAVASCRIPT
const emptyArray = []; const nonEmptyArray = [1, 2, 3]; console.log(emptyArray.length); console.log(nonEmptyArray.length);
BASH
0 3

Therefore, if you want to check if the array is empty or not, we can do a simple if statement.

JAVASCRIPT
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'); }
BASH
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:

JAVASCRIPT
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'); }
BASH
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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.