This is a question that comes up from time to time, and is sometimes a surprising answer.
“Falsy” is a term that generally means “These terms act as if they are
false when used in comparisons”. There’s a corresponding term
“Truthy” which generally means “everything else acts like
true”. These terms are used across many different languages, both
typed and untyped.
In Types & Grammar: Falsy Values, Kyle explains how things get defined as Falsy:
- values that will become
falseif coerced to
- everything else (which will obviously become
I’m not just being facetious. The JS spec defines a specific, narrow list of values that will coerce to
falsewhen coerced to a
How do we know what the list of values is? In the ES5 spec, section 9.2 defines a
ToBooleanabstract operation, which says exactly what happens for all the possible values when you try to coerce them “to boolean.”
From that table, we get the following as the so-called “falsy” values list:
- +0, -0, and
That’s it. If a value is on that list, it’s a “falsy” value, and it will coerce to
falseif you force a
booleancoercion on it.
By logical conclusion, if a value is not on that list, it must be on another list, which we call the “truthy” values list. But JS doesn’t really define a “truthy” list per se. It gives some examples, such as saying explicitly that all objects are truthy, but mostly the spec just implies: anything not explicitly on the falsy list is therefore truthy.
foo is not explicitly a
boolean value, such as
undefined, when checking to make sure you’re not operating on
such a value, it is coerced into one (using that
mentions above.) This idiom is used a lot in functions as a guard
clause to prevent mischief from callers.
You might also see this instead of an early return:
Of course, with both of these idioms, there can be problems with some
of the other definitions for falsy: what happend when you intend to
pass in a value of
In such a case, I step back and stop using coercion and go for explicitness, and the idiom becomes:
So there we have it. The ECMAScript specification Kyle refers to above is at http://www.ecma-international.org/ecma-262/6.0/#sec-toboolean if you’re interested in reading it.
If you found this useful, please go visit Kyle’s site You-Dont-Know-JS and give him some love. Buy the books, become a patreon!