Matt Snider JavaScript Resource

Understanding JavaScript and Frameworks

Sunday, April 8, 2007

True, Truthy, WTF

As you probably know, JavaScript has keywords for true and false. These keywords are of the quasi-type ‘boolean’ and can be detected with my isBoolean() function that uses the ‘typeof’ keyword. What you may not know is that JavaScript, like many C-style derived languages, has the concepts of truthy and falsy. This concept is important because most of the JavaScript Frameworks, which we will soon be analyzing, make use of this feature.

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.

from TruthyFalsyAndTypeCasting

For an in-depth look at the concept ‘truthy’ vs the ‘keyword’ true, I created this test page: False Vs. Falsy Test Page

The best practice approach, is to use the keywords true and false, and try to avoid code that uses 0 and 1 for the purposes of truthy and falsy. It is acceptable to use truthi-/falsiness to determine if a variable does not have a value:
var obj;
if (obj) {
// do something
}
else {
// error management code
}

posted by Matt Snider at 5:49 pm  

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment

Powered by WordPress