Limitless

Limitless

Check for Empty Array in Javascript

Check for Empty Array in Javascript

Subscribe to my newsletter and never miss my upcoming articles

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
Β 
Share this