Quantcast
Channel: Why do empty JavaScript arrays evaluate to true in conditional structures? - Stack Overflow
Viewing all articles
Browse latest Browse all 8

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

$
0
0

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.


Viewing all articles
Browse latest Browse all 8

Latest Images

Trending Articles





Latest Images