Tuesday, February 28, 2006

Shades of Truth and Falsity

Earlier, I mentioned that you never need new Boolean to create a boolean value. That's because Javascript rarely needs boolean values at all; it will gladly make boolean decisions based on any type of variable--numbers, strings, even objects!

When used in a context that needs a boolean value, Javascript considers these values--and only these values--to be false:

false (the boolean kind)
0 (numeric zero)
null (the null value)
undefined (the undefined value)
NaN (the not-a-number value)
"" (an empty string)

Anything else is considered to be a true value. Anything. Really. Memorize the entire set of potentially false values, it will make your Javascript better. Be careful, Javascript will not automagically convert values from another type when it evaluates their booleanosity. String values of "0", "false", or "null" evaluate to true. In contrast, an expression like parseInt("0") returns numeric zero and evaluates to false. Then again, parseInt("null") returns NaN (it's not a number, obviously) and that is also false.

One common use of the undefined value is to check for the existence of properties in an object. Thus, you'll often see if ( document.getElementById ) to check browser support for a DOM function. The value will either be undefined or a function object, which are interpreted as false/true respectively. Note that this trick won't work to check for undefined variables. If a variable has never been defined, Javascript will give you an error. The safe way to check for a variable that has never been declared is to use typeof(nosuchvar)=="undefined".

It's worth learning the boolean drill backwards and forwards, because knowing these rules comes in mighty handy with the next topic: short-circuit evaluation.

No comments: