Control flow
if, else and the ternary operator
Goal: Branch with if/else and the conditional operator · 8 min
if (score >= 90) {
grade = "A";
} else if (score >= 75) {
grade = "B";
} else {
grade = "C";
}
Conditions go in parentheses, blocks in curly braces. Logical operators: && (and), || (or), ! (not).
For a simple choice between two values use the ternary operator: const label = age >= 18 ? "adult" : "minor";
?? (nullish coalescing) supplies a default only for null/undefined: name ?? "guest".
Worked example: Shipping cost
- Orders from 50 € ship free.
- 42 < 50, so shipping is 4.99.
- Output:
46.99
const order = 42;
const shipping = order >= 50 ? 0 : 4.99;
console.log(order + shipping);Output:
46.99