In JavaScript, values are divided into two categories: truthy and falsy. These terms refer to how values behave when evaluated as a boolean.
truthyvalues evaluate as true valuesfalsyvalues evaluate as false values
This automatic conversion happens when the value is used in a context that expects a boolean (for example, when used as a condition in a conditional statement, or compared with an operator).
truthy and falsy are two concepts used very frequently in JavaScript. But don’t worry, they are very easy to understand.
If the words seem a bit absurd to you, don’t worry… you’re not the only one 😄
Falsy Values
falsy values are those that, when evaluated in a boolean context, are considered as false.
There are only six values in JavaScript that are considered falsy:
false: The boolean valuefalseis obviously falsy.0: The number zero is falsy.""(empty string): A string without characters is falsy.null: Represents the absence of any value and is falsy.undefined: Means a variable has been declared but not assigned, and is falsy.NaN: Means “Not-a-Number” which is falsy (it’s 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 as 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 the 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 (maybe they get charged per letter 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,
usernameis evaluated directly in theifcondition.- If
usernameis a non-empty string (truthy), the first branch will execute. - If it is an empty string (
falsy), the second branch will execute.
Let me say this… don’t do that. Don’t rely on automatic conversions to booleans.
If you want to perform a check, do it correctly. Because later someone changes something in the code, and your conditional starts working incorrectly.
