True vs Truthy


JavaScript has keywords for true and false. These keywords are of the meta-type boolean and can be detected with 'boolean' === typeof object. What you may not know is that JavaScript, like many C-style derived languages, has a concept of truthy and falsy. This concept is important because many JavaScript code snippets and frameworks make use of this feature of the language.

“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, while trying to avoid code that uses truthy and falsy. However, it is common practice and acceptable to use truthi-/falsiness to determine if a variable has a value:

Example 1: Truthy

var obj;
if (obj) {
// do something
}
else {
// error management code
}