Check for Empty Array in Javascript

Hi there 👋🏾. I'm a software engineer that enjoys building stuff and talking about them. I also tinker a bit with hardware and robotics using Arduino and ROS.
Checking that an array is empty in Javascript involves more than using !array. This is because an array is an object and you cannot simply negate an object in a conditional. With that said, the code block below will never run.
const countries = []
if (!countries) {
console.log("No country has been added")
}
Checking that an array is empty in a conditional
To test for an empty array, you use the length method, either by
- Comparing the length to zero using
=== - Simply negating the length
Comparing the length to zero
Using our countries example, we can test for emptiness using
const countries = []
if (countries.length === 0) {
console.log("No country has been added")
}
This code is readable and clean enough.
Negating the length
If you like shorter code, you can simply negate the length using
const countries = []
if (!countries.length) {
console.log("No country has been added")
}
This works because 0 is a falsy value in Javascript. Negating a falsy value returns true. Thanks for stopping by. Adios ✌🏾🧡.
Credits
- Cover illustration by Freepik
