How to check if an array is empty

JavaScript polyfill, by , Friday, March 7th, 2014

Checking if an array is empty in JavaScript is very easy. All you need to do, is to check the length of the array;

  1. // Presuming we have an array declared named "arr",
  2. // this is how you could check if it is empty
  3. if (arr.length) {
  4. // The array is empty
  5. } else {
  6. // The array is NOT empty
  7. }

What happens in the code above is, that if the length of the array arr is 0 it is empty, and the if statement works, because 0 is a falsy value in JavaScript. (for more information about truthy and falsy values in JavaScript, you can read my article Primitive types, and truthy and falsy values from my JavaScript Ground up tutorials)