Here's something interesting. The condition inside an if doesn't have to be an actual boolean. You can put any value in there, and JavaScript will decide whether it counts as "true-ish" or "false-ish."
Values that count as false are called falsy. There are only eight of them, so you can actually memorize this list:
| Falsy value | What it is |
|---|---|
false | The boolean false |
0 | The number zero |
-0 | Negative zero (yes, that exists) |
0n | BigInt zero |
"" | The empty string |
null | Deliberately empty |
undefined | Not given a value |
NaN | Not a Number |
Everything else is truthy. Every non-empty string, every number except zero, every list, every object. All truthy.
if ("hello") {
console.log("Non-empty strings are truthy");
}
if (42) {
console.log("Non-zero numbers are truthy");
}
if ("") {
console.log("You will never see this");
}
if (0) {
console.log("Or this");
}
It prints
Non-empty strings are truthy Non-zero numbers are truthy
You can see whether something is truthy or falsy by converting it with Boolean():
console.log(Boolean("pizza"));
console.log(Boolean(""));
console.log(Boolean(0));
console.log(Boolean(-5));
console.log(Boolean(null));
It prints
true false false true false
Why is this useful?
It lets you write short, readable checks. For example, "did the user actually type something?"
const username = "";
if (username) {
console.log(`Hello, ${username}!`);
} else {
console.log("Please enter a username.");
}
It prints
Please enter a username.
Since the empty string is falsy, if (username) means "if the username isn't empty." Neat!
"0" and "false" are truthy! They're non-empty strings. It doesn't matter what characters are inside; any string with at least one character is truthy. So if a value comes from a prompt or a form, it's a string, and "0" will count as true. Convert it with Number() first if you want to treat it as a number.