Search code examples
javascriptarraysobjectconditional-statements

Why do empty JavaScript arrays evaluate to true in conditional structures?


I was encountering a lot of bugs in my code because I expected this expression:

Boolean([]); to evaluate to false.

But this wasn't the case as it evaluated to true.

Therefore, functions that possibly returned [] like this:

// Where myCollection possibly returned [ obj1, obj2, obj3] or []
if (myCollection)
{
  // ...

} else
{
  // ...
}

did not do expected things.

Am I mistaken in assuming that [] an empty array should evaluate to false?

Also, Is this behavior consistent in all browsers? Or are there any gotchas there too? I observed this behavior in Google Chrome by the way.


Solution

  • From http://www.sitepoint.com/javascript-truthy-falsy/

    The following values are always falsy:

    • false
    • 0 (zero)
    • 0n (BigInt zero)
    • "" (empty string)
    • null
    • undefined
    • NaN (a special Number value meaning Not-a-Number!)

    All other values are truthy, including "0" (zero in quotes), "false" (false in quotes), empty functions, empty arrays ([]), and empty objects ({}).

    Regarding why this is so, I suspect it's because JavaScript arrays are just a particular type of object. Treating arrays specially would require extra overhead to test Array.isArray(). Also, it would probably be confusing if true arrays behaved differently from other array-like objects in this context, while making all array-like objects behave the same would be even more expensive.