An upcoming article I'll be doing for Smashing Magazine will look at the oddities and gotchas of Javascript — and lordie does it have a few.
One of these is the concept of
truthy and falsy. These are sort of like true/false-lite, which will anger you somewhat if you majored in logic or philosophy. You mean you didn't know true and false were in fact gradable, not absolute concepts!?
In Javascript, every value has an in-built flag
denoting its boolean equivalent. This is called upon when you ask the value to behave like a boolean, e.g. by comparing it to a real boolean. Javascript
coerces your value into a boolean, such that the comparison is possible (after all, you can't compare apples with pears). See below for more on data coercion. So:
var someVar = 0;
alert(someVar == false); //evaluates true
Since we are attempting to compare zero to a boolean, Javascript coerces the zero to its truthy/falsy equivalent — and zero is a falsy (along with null, undefined, NaN, empty strings and false — everything else is a truthy). So the expression effectively becomes:
alert(false == false); //evaluates true, of course
It's important to realise that this does not mean your value is a boolean — it simply means Javascript temporarily converts it to a boolean to make the comparison possible. If we did the same comparison with the === operator (which compares not only by value
but also by type), the result would be different:
alert(someVar === false); //evaluates false - someVar is a number, not a legitimate boolean
It gets worse
Clear enough? It gets more complex.
A well known quirk of Javascript is that an empty array appears to be equal to false.
(
Read more
)