Free Handbook · Runs in your browser

Flow Control

if / else and switch, the four loops and when each is right, break and continue, for…of versus for…in versus forEach, truthiness in conditions, and the infinite loop and = vs === mistakes that every beginner makes once.

0 / 111 lessons🔥 0 day streak
ShareXLinkedIn

Module 02 · what you'll be able to do

  • Branch with if / else if / else, the ternary and switch
  • Choose between for, for…of, while and do…while
  • Use break, continue and labels correctly
  • Know why for…in is for objects and for…of is for arrays
  • Recognise an infinite loop and an assignment-in-condition bug on sight
01

if, else if, else

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
Warm
empty
but [] itself is truthy!
B
pass
no user anonymous user Ada
Your turn
Write fizzbuzz(n) for 1–15: multiples of 3 print Fizz, of 5 print Buzz, of both print FizzBuzz. Order of the checks matters — why?
VisualizeHow an if / else if chain is evaluatedStep 1 / 4
const temperature = 31
if (temperature > 35) {
console.log("Heat warning")
} else if (temperature > 25) {
console.log("Warm")
} else {
console.log("Cold")
}
Line 1

Bind temperature to 31.

Variables now
temperature31
All 4 steps as a table
StepLineWhat happenedVariables now
11Bind temperature to 31.temperature = 31
22Evaluate 31 > 35 → false. Skip this block.
34Evaluate 31 > 25 → true. Enter this block.
45Print. Then jump past the whole chain — the else is never considered.
Error you will hit

Assignment in a condition: if (x = 5)

javascript
let role = "guest"
if (role = "admin") {
  console.log("access granted")
}
console.log(role)
access granted
admin
Why the engine said that

No error — a silent bug. = assigns; the expression role = "admin" evaluates to "admin", which is truthy, so the block always runs and role is now "admin". You meant ===.

The fix

Use ===. Linters flag no-cond-assign; turn ESLint on from day one (Module 14).

javascript
let role = "guest"
if (role === "admin") {
  console.log("access granted")
}
console.log(role)   // guest
02

switch

switch compares one value against several cases with ===. It reads better than a long else if chain of equality checks — and it has one trap: without break, execution falls through into the next case. Sometimes that is what you want (grouping cases); usually it is a bug.

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
weekend almost weekday
one
two
stopping
Rule
Every case ends in break or return, unless you write // falls through on purpose. For mapping a value to a result, a plain object (lookup[key]) is shorter and cannot fall through.
03

for and for…of

The classic three-part for is for when you need the index or a counter. for…of is for "each item in this array (or string, Map, Set)" and is what you should write by default — no index, no off-by-one. The array methods forEach, map and filter (Module 04) cover the rest.

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
i = 0
i = 1
i = 2
APPLE
BANANA
CHERRY
0 apple
1 banana
2 cherry
h
i
a 1
b 2
10
7
4
1
34.49
Your turn
Print the multiplication table for 7 (7 × 1 … 7 × 10) using a for loop and a template literal.
VisualizeSumming an array, one iteration at a timeStep 1 / 9
let total = 0
for (const n of [3, 5, 9]) {
total += n
}
console.log(total)
Line 1

Start the accumulator at 0.

Variables now
total0
All 9 steps as a table
StepLineWhat happenedVariables now
11Start the accumulator at 0.total = 0
22Take the first item: n is 3. (A fresh const n each iteration.)n = 3
33total += n → 0 + 3.total = 3
42Next item.n = 5
533 + 5.total = 8
62Last item.n = 9
738 + 9.total = 17
82No items left — the loop ends.
95Print.
Error you will hit

for…in on an array gives you string keys, not items

javascript
const scores = [90, 85, 77]
let total = 0
for (const s in scores) {
  total += s
}
console.log(total)
0012
Why the engine said that

No error, wrong answer. for…in iterates property names ("0", "1", "2" — strings), so total += s concatenated. for…in is for plain objects, and even there Object.keys is usually clearer.

The fix

Use for…of for arrays, strings, Maps and Sets.

javascript
const scores = [90, 85, 77]
let total = 0
for (const s of scores) total += s
console.log(total)   // 252
04

while and do…while

while repeats as long as a condition holds — the natural loop when you do not know how many iterations you need: retry until success, read until end of input, halve until below a threshold. do…while runs the body at least once before checking.

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
steps: 111
attempt 1: retry
attempt 2: retry
attempt 3: ok
got y
[ 4, 3, 2, 1 ]
Your turn
Write a loop that prints the powers of 2 below 1000. Then rewrite it with for. Which reads better?
Error you will hit

The infinite loop: the condition never becomes false

javascript
let i = 0
while (i < 5) {
  console.log(i)
  // forgot i++
}
0
0
0
… (the tab freezes; this page kills it after 10 seconds)
Why the engine said that

Nothing inside the loop changes i, so i < 5 is true forever. In a browser tab this hangs the page — the reason this handbook runs your code in a worker it can terminate.

The fix

Every while needs something in the body that moves toward the exit. If the count is known, use for — the increment lives in the header where you cannot forget it.

javascript
let i = 0
while (i < 5) {
  console.log(i)
  i++
}
05

break, continue and labels

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
first over 10: 15
odd 1
odd 3
odd 5
found at 1,2
-1 null
15 [ 1, 3 ]
break does not work inside forEach
forEach takes a callback; break inside it is a SyntaxError and return only leaves the callback. If you need to stop early, use for…of, find, some or every.
06

for…in, forEach and which loop to use

javascriptEdit it. ⌘/Ctrl + Enter runs.
You should see
name → Ada
age → 36
role → admin
name=Ada
age=36
role=admin
[ 'name', 'age', 'role' ] [ 'Ada', 36, 'admin' ]
0 a
1 b
[
  { need: 'each array item', use: 'for…of' },
  { need: 'index too', use: 'for or entries()' },
  { need: 'object keys', use: 'Object.entries' },
  { need: 'unknown count', use: 'while' },
  { need: 'new array from old', use: 'map / filter (Module 04)' }
]
Quick check

You want to loop over the items of an array and stop at the first match. Which loop?

JuniorWhat is the difference between for…in and for…of?

for…in iterates the enumerable property names of an object (strings), including inherited ones. for…of iterates the values of anything iterable — arrays, strings, Maps, Sets, generators. Use for…of for arrays; for objects use Object.entries with for…of.

Finish the JavaScript handbook, then get hired

Sit the exam for your certificate, run your resume through the ATS checker, and see the jobs that ask for exactly this.

Check my resume
Found this course useful? Share it.
ShareXLinkedIn

Comments

0

Join the conversation. Sign in to leave a comment — we'd love to hear your thoughts.