[Advert: Support Joe Clark's Micropatronage Project - support accessible media research]

Syndicated feed for Javascript

Weblogs: Javascript

The most popular client-side scripting language - often overused and maligned. Unobtrustive Javascript is slowly gaining ground as a better way of enhancing html pages with dynamic features.


Monday, October 02, 2006

Truthy, falsy and type-casting

JavaScript has keywords for true and false, but like many C-style derivative languages, it has concepts of truthy and falsy. These are non-boolean expressions that can be treated as a boolean value. The number zero is falsy, and any other number is truthy. Equally for strings, an empty string is falsy, and a non-empty string is truthy.

JavaScript also has the neat type-conversion functions. Strings containing numbers can be coerced into being just numbers. When combined with truthy and falsy logic, things can get a little surprising, and there are a few gotchas to avoid.

Expression Evaluation Reason
true true true is always true
false false false is always false
1 true non-zero numerics are truthy
0 false the numeric zero is falsy
'1' true a non-empty string is always truthy
'0' true a non-empty string is always truthy
1 - 1 false a numeric value of zero is falsy
'1' - '1' false The minus coerces both strings into being integers, and so a numeric value of zero is falsy
'0' + '0' true The plus does string concatenation, so the end result is a two character string, which is truthy
0 + '0' true The plus does string concatenation, so the end result is a two character string, which is truthy
0 + 0 false Because both operands a numerics, the plus does numerical addition, so the end result is zero, which is falsy

For a best practice approach, it makes sense to use the keywords true and false, and try to avoid code that uses 0 and 1 for the purposes of truthy and falsy. A common scenario this situation arises is when JavaScript is dynamically generated by a server-side language where the string '0' is treated as numeric in expressions.


Older Posts:


[ Weblog Frontpage | Blog categories and feeds | 2007 | 2006 | 2005 | 2004 | 2003 | 2002 ]