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:
if (x) { ... }would always evaluate like if (x == true) { ... }
I was wrong. For example, if ([]) { ... }evaluates to true, but if ([] == true) { ... } evaluates to false.
I wrote the following test to help me identify other perilous JavaScript irregularities.
Read the squares as:
if (y)
green
else
red
Labels: javascript