Search code examples
javascriptif-statementnumbersboolean

Java Script: Array.length expression evaluate to boolean


How to check array length, if I need the expression to evaluate to boolean value as a result? For example:

var myArray = [];
if(!myArray.length){
  return;
}

Or:

vr myArray = [];
if(myArray.length == 0){
  return;
}

Both of the examples work, however I’d like to understand what is the difference?


Solution

  • Here !myArray.length will return true in two cases:

    • If myArray.length===0 because 0 is a falsy value, so !0 will return true.
    • If myArray.length is undefined, in other words myArray is not an array so it doesn't have the length property, where undefined is falsy value too.

    And the first one explains why both !myArray.length and myArray.length==0 are equivalent in your case.