An if statement is a bouncer at a club door. Every value that walks up gets asked if it's truthy. Truthy values get in, and falsy values get turned away. Sorry, zero.
Why values turn into true or false
An if needs a yes or a no. But you can hand it anything, like a number, a string or an array. So JavaScript first turns the value into a boolean, which just means true or false. Values that become true are called truthy. Values that become false are called falsy.
const cookies = 0;
let mood = "sad";
if (cookies) {
mood = "happy";
}
console.log(mood); // prints: sad
cookies is 0, and 0 is falsy, so the bouncer turns it away and the code inside the braces never runs.
The six falsy values
Only a few values are falsy. Remember these six:
false0""(an empty string)nullundefinedNaN
Everything else is truthy. There are two rare cousins of zero that are falsy too, -0 and 0n (zero written as a BigInt). They are just more zeros.
It's easier to remember the short falsy list than to think about every value that could be truthy. Any number other than zero, any string with at least one character, every array and every object will get past the bouncer.
The traps
Some values look false but aren't on the list, so they get in.
- The string
"0"is truthy. It isn't empty, it has a character in it. - The string
"false"is truthy. It's still text with letters in it. - An empty array
[]is truthy. Arrays are objects, and objects always count as truthy, even empty ones. The same goes for{}.
In the == lesson, [] == false came out true. That's double equals converting things with its own rules. The bouncer doesn't do that. It only asks whether the value is on the falsy list.
The twist: ask the bouncer directly
Boolean is JavaScript's word for true or false. Wrap any value in Boolean() and you see what the bouncer thinks of it. The short version is two exclamation marks in front, called double bang. One means not, so two means not not, which flips the value twice and leaves a plain true or false.
console.log(Boolean("hi")); // prints: true
console.log(Boolean("0")); // prints: true
console.log(Boolean([])); // prints: true
console.log(!!0); // prints: false
console.log(!!""); // prints: falseUsing it in real code
Truthy checks are handy for questions like "is there anything here?" For example, if (name) skips an empty name.
Be careful when 0 or an empty string is a real answer. A score of 0 is falsy, so if (score) treats a real score as missing. In that case check exactly what you mean, such as typeof score === "number".
Rule of thumb
Memorize the six falsy values, and everything else is truthy.
Checking text from a form with if (input) and expecting "0" or "false" to be skipped. Both are non-empty strings, so both are truthy. Convert the text first, for example with Number(input), then check.
Check yourself
The empty string is on the falsy list. "0" and "false" are non-empty strings, and arrays are always truthy.