Skip to main content

Command Palette

Search for a command to run...

Check for Empty Array in Javascript

Published
2 min read
Check for Empty Array in Javascript
O

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

  1. Comparing the length to zero using ===
  2. 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

  1. Cover illustration by Freepik

More from this blog

O

Osinachi's base

66 posts

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.