Wednesday, August 19, 2009
Oddities of Boolean evaluation in JavaScript
I had some naive notions about how JavaScript evaluated certain Boolean expressions. For example, I assumed that code like
I wrote the following test to help me identify other perilous JavaScript irregularities.
Read the squares as:
would always evaluate likeif (x) { ... }
I was wrong. For example,if (x == true) { ... }
evaluates to true, butif ([]) { ... }
evaluates to false.if ([] == true) { ... }
I wrote the following test to help me identify other perilous JavaScript irregularities.
Read the squares as:
if (y)
green
else
red
Labels: javascript