Control Flow — if · for · while · switch
Control Flow — if · for · while · switch
🎯 After reading this lesson
After finishing this lesson, you will be able to confidently do the following 3 things.
- ▸✅ Know when to use if-else · switch · ternary
- ▸✅ Understand the critical difference between ?? (nullish) and || (falsy)
- ▸✅ Know the
awaitcompatibility of for · for-of · for-in · forEach
Keep the learning objectives as a checklist — close the lesson only when you can answer all of them.
if / else / ternary — 3 ways to express a *branch*
The most basic if
Conditions are evaluated as truthy/falsy. 0, '', null, undefined, NaN, false are falsy. Everything else is truthy.
Ternary operator — shorthand for a brief if
An if that returns a value. Very common inside React JSX:
Triple ternary (a ? b : c ? d : e) hurts readability — avoid it. Use if-else instead.
Optional chaining + Nullish coalescing — shorthand branching
?. — if the left side is null/undefined, immediately returns undefined (avoids TypeError).?? — uses the right side only when the left is null/undefined. 0 or '' are used as-is.
The difference from || is a classic vibe-coding trap. 80% of AI-generated code uses ??.
4 types of loops — for · while · for...of · for...in
Classic for
Useful when you need to manipulate the index directly (reverse iteration, skipping).
while / do-while
For dynamic conditions (waiting for input, retry loops). For general iteration, for-of is better.
for...of — iterate over values (arrays)
The most commonly used array loop. break and continue are supported (a key difference from forEach).
for...in — iterate over keys (objects)
Note: Using for...in on an array gives string indices and may include inherited properties — use for...of for arrays, for...in for objects (or Object.entries).
break · continue
Difference between forEach and for...of — a classic vibe-coding question
Rule: If you need await or break, use for...of; for simple transformations, use map/filter/reduce (forEach is becoming less common).
switch — the fall-through trap
Basic switch
The fall-through trap
With day === 'MON', both "Monday" and "Tuesday" are printed. Missing break is the #1 cause of bugs.
Intentional fall-through — grouping multiple cases
Object literal as a replacement — more modern
When if-else or switch chains get long, object mapping is cleaner:
A pattern commonly used in JSX/React component branching.
🤖 Try asking AI like this
- ▸"Convert this if-else chain into a switch"
- ▸"Check this switch for possible missing breaks"
- ▸"Refactor this branch into an object mapping"
Knowing control flow lets you precisely direct AI to transform logic, and catch bugs in AI-generated code.