How to make decisions with if/else
Use if and else
The if block runs when its condition is truthy; otherwise the else block runs.
const age = 17;
if (age >= 18) {
console.log("Adult ticket");
} else {
console.log("Youth ticket");
}
Test several cases
Place the most specific conditions first. Only the first matching branch runs.
const score = 82;
if (score >= 90) {
console.log("Excellent");
} else if (score >= 70) {
console.log("Passed");
} else {
console.log("Keep practicing");
}
Use a conditional expression
The ternary operator is useful for choosing one of two values. Use normal branches when logic needs several statements.
const isOnline = true;
const label = isOnline ? "Available" : "Offline";
console.log(label);
Write dependable conditions
- Use braces even for a one-line branch
- Prefer strict equality
- Name complex conditions before testing them
- Handle boundary values such as exactly 18 or an empty input