Truthy & Falsy Values
true or a boolean
Unlike other languages,
false values are not limited to
boolean data types and comparisons. It can have many other forms.
Truthy expressions always evaluate to boolean
true and falsy evaluate to boolean
true. Rather, what we mean is that the value coerces to
true when evaluated in a boolean context. Let's look at what that means.
The easiest way to learn truthy and falsy values is to memorise falsy values only. There are only six falsy values, all the other values are truthy.
Let's explore the list of falsy values:
- 0 (zero)
- "", '', `` (empty strings)
- NaN (not a number)
note : Empty array () is not falsy
- Everything that is not FALSY
That's a pretty straightforward list. But how can we actually use truthiness? Let's look at an example.
Taking advantage of truthiness can make your code a little bit more concise. We don't need to explicitly check for
"", etc. Instead we can just check whether a value is truthy. However, there some caveats to keep in mind.