Conditionals and Control Flow
Branch program logic with if/else, switch, ternary expressions, and guard clauses — the patterns production code actually uses.
Control flow is how programs make decisions. Bad branching — pyramid else chains, magic booleans, nested ternaries — is one of the fastest ways to create unmaintainable modules. This lesson covers the syntax (if, switch, ternary) and the style senior teams expect: guard clauses, explicit comparisons, and choosing the right construct for readability.
if / else — the decision tree
switch compares one expression against many case labels using strict equality (===). When a case matches, execution falls through to the next case unless you break or return. Fall-through is powerful for grouping (401 and 403 share handling) but dangerous when accidental — always comment intentional fall-through. default catches no match; omitting it means silent no-ops when a new enum value appears.
8
0switch — multi-way branching
switch compares one value against many case labels using strict equality (===). Every case needs break unless fall-through is intentional.
Unauthorized
Unknown statusTernary operator — expression, not statement
The example below demonstrates "Ternary operator — expression, not statement" in runnable form. Read the comment lines first — they map each step to the mental model from earlier sections, then trace execution top to bottom as the engine would.
Administrator
B
dev@acedevhub.comTruthy checks vs explicit comparisons
The ternary operator (condition ? a : b) is an expression — it produces a value you can assign or return. That makes it ideal for simple UI labels and config picks. The moment you nest ternaries three levels deep, switch to if/else or a lookup table. Expressions should fit on one screen line in code review.
Nothing to process
Processing 2 itemsOptional chaining in conditions
Truthy checks (if (value)) are concise but imprecise. Empty arrays, empty objects, and the string "0" are all truthy. APIs should validate shape explicitly: Array.isArray, typeof x === "string", Number.isFinite. Optional chaining (?.) short-circuits property access when intermediate values are null or undefined — it prevents the classic "Cannot read property of undefined" without six nested ifs.
Pro features enabled
lightWhen branches grow beyond three levels, extract named functions or lookup tables instead of nesting. Switch works well for discrete enums; if/else chains suit ranged conditions like age tiers. The goal is a control flow readers can scan in one pass during incident response.
- 1Prefer guard clauses over deep else nesting
- 2switch uses ===; always break or comment fall-through
- 3Ternary for simple value picks; if/else for complex branches
- 4Check arrays with .length, not bare truthiness
- 5Next lesson: for, while, and iteration patterns