In JavaScript, values are divided into two categories: truthy
and falsy
. These terms refer to how values behave when evaluated as a boolean.
truthy
values evaluate as true valuesfalsy
values evaluate as false values
This automatic conversion occurs when the value is used in a context that expects a boolean (for example, when used as a condition in an if statement, or compared with an operator).
truthy
and falsy
are two concepts that are widely used in JavaScript. But don’t worry, they are very easy to understand.
If these little words seem a bit absurd to you, don’t worry… you are not alone 😄
Falsy Values
falsy
values are those that, when evaluated in a boolean context, are considered false
.
There are only six values in JavaScript that are considered falsy
:
false
: The boolean valuefalse
is obviously falsy.0
: The number zero is falsy.""
(empty string): A string with no characters is falsy.null
: Represents the absence of any value and is falsy.undefined
: Means that a variable has been declared but not assigned, and is falsy.NaN
: Stands for “Not-a-Number” which is falsy (it is the result of an invalid mathematical operation)
Let’s see it with an example,
if (!0) {
console.log("0 is a falsy value");
}
if (!null) {
console.log("null is a falsy value");
}
Truthy Values
truthy
values are those that, when evaluated in a boolean context, are considered true
.
Any value that is not falsy
is considered truthy
. This includes practically everything else:
- Numbers other than 0: All numbers different from
0
, whether positive or negative - Non-empty strings: Any string with at least one character, including “0” or “false”
- Objects and arrays: Any object or array, even empty ones
- The boolean value
true
: Obviously 😉
For example,
if ("hello") {
console.log("A non-empty string is truthy");
}
if ({}) {
console.log("An empty object is truthy");
}
Importance of Truthy and Falsy
In JavaScript (and in other languages to a lesser extent), some programmers have a habit of relying on the implicit evaluation of these properties to “simplify” the code.
This way they save themselves from explicitly comparing with true
or false
(they must be charged for the letters or something)
For example:
let username = "John";
if (username) {
console.log("The user has provided a name");
} else {
console.log("The username is empty");
}
In this code,
username
is evaluated directly in theif
condition.- If
username
is a non-empty string (truthy
), the first branch will execute. - If it is an empty string (
falsy
), the second branch will execute.
Let me put it this way… don’t do that. Don’t rely on automatic conversions to booleans.
If you want to make a check, do it correctly. Because later they change anything in the code, and your conditional stops working correctly.