Making Decisions with if/else
Programs need to react differently depending on the situation, that's what if/else is for.
JavaScript
The pieces
if (condition) { ... }runs its block only whenconditionistrue.else if (condition) { ... }checks another condition, only if every earlier one wasfalse.else { ... }runs when none of the earlier conditions matched, it's the fallback.- Conditions are usually built from comparison operators (
>=,===, ...) and can be combined with&&(and, both must be true) and||(or, at least one must be true).
JavaScript
Truthy and falsy
Values other than actual booleans still work inside an if, 0, "" (empty string), and null all act like false, almost everything else acts like true. This is handy for quick checks like if (name) { ... } (runs only if name isn't empty), but can also be surprising if you're not expecting it.