Is an empty box a yes?
An if doesn't only accept true and false. You can give it any value — a number, a string — and JavaScript decides whether it *counts as* true. This is the secret behind lots of short, tidy code.
The six falsy values
Only a few values count as false. They're called falsy:
- false
- 0
- "" (an empty string)
- null
- undefined
- NaN
Everything else is truthy — including "0", "false", -1 and " " (a space).
const name = "";
if (name) {
console.log("Hello, " + name);
} else {
console.log("Please type your name.");
}
console.log(Boolean("momo"));
console.log(Boolean(0));The empty plate: Ask "is there food on the plate?" An empty plate ("") or zero momos (0) means no. Any amount, even one sad momo, means yes.