Control Flow & Loops
Lesson opener
In one line: If/else if/else - telling the program which branch to run.
Why it matters: This shows up at work when you need to if/else if/else - telling the program which branch to run.
Before this lesson: Variables, types & operators
Before you start
| Resource | Link |
|---|---|
| Previous | Variables, types & operators |
| Next | Functions & scope |
| Time | ~25 minutes |
What you will learn
if/else if/else— telling the program which branch to runforandwhile— repeating code a set number of times (or until a condition changes)breakandcontinue— controlling the loop from the inside
Section 1 — if, else if, and else
Programs make decisions. The if statement says: if this comparison is true, run this block; otherwise do something else.
let score = 82
if (score >= 80) {
console.log("Distinction")
} else if (score >= 60) {
console.log("Pass")
} else {
console.log("Try again")
}Expected result: Distinction
Plain English breakdown:
if (score >= 80)→ check the condition in parentheses{ ... }→ the block that runs only if the condition is trueelse if→ secondary checks, in order, skipped as soon as one matcheselse→ the final catch-all, runs only if every earlier condition was false
Why it matters at work: Every dashboard is full of these — "if the region is EU use tax rule A, else use rule B"; "if the API returns 404 show a retry"; "if the value is null skip the row." Conditionals shape business logic.
Section 2 — Using booleans directly
If a variable already is a boolean, you can use it directly — no comparison needed.
let isAdmin = true
if (isAdmin) {
console.log("Admin panel unlocked")
}Expected result: Admin panel unlocked
Common mistake: Writing if (isAdmin === true). The === true is redundant. Use if (isAdmin) — it reads clearer for exactly the same result.
Section 3 — for loops
A for loop repeats a block a known number of times. It has three parts: the start (let i = 0), the condition (i < 5), and the step (i++).
for (let i = 0; i < 5; i++) {
console.log(`Count: ${i}`)
}Expected result:
Count: 0
Count: 1
Count: 2
Count: 3
Count: 4Plain English breakdown of ONE iteration:
let i = 0→ runs once at the very starti < 5→ checked before every iteration- run the block
i++→ runs after the block, adds 1 toi- back to step 2 — until
i < 5is false
Why it matters at work: Everything you repeat a fixed number of times is a for loop — generate 52 weekly rows, loop over N files, process each row of a report.
Section 4 — while loops
A while loop repeats as long as a condition stays true. You use it when you do not know ahead of time how many repeats you need.
let retries = 0
while (retries < 3) {
console.log(`Attempt ${retries + 1}`)
retries++ // ← critical: must eventually make the condition false
}Expected result:
Attempt 1
Attempt 2
Attempt 3Common mistake — infinite loop: Forgetting to update the condition inside the loop. If retries++ is missing, retries stays 0, the condition retries < 3 is always true, and the loop never stops — freezing your script.
let x = 0
// DANGER: never increments x — this loop runs forever
// while (x < 3) {
// console.log("stuck")
// }If your script hangs, check for a while loop missing its progress step.
Section 5 — break and continue
break→ stop the loop entirely (exit immediately)continue→ skip this one iteration and move to the next
for (let i = 1; i <= 10; i++) {
if (i === 4) continue // skip 4
if (i === 8) break // stop at 8
console.log(i)
}Expected result:
1
2
3
5
6
7Plain English: continue on 4 skips printing it. break on 8 stops the whole loop, so 8, 9, 10 never print.
Why it matters at work: break is how you stop processing after finding the answer you wanted ("first matching customer, then quit"). continue is how you skip rows you should not process ("ignore empty cells").
Section 6 — Looping over arrays
This is the pattern you will use constantly — run the loop body once per item in a list.
let customers = ["Priya", "Rana", "Ana"]
for (let i = 0; i < customers.length; i++) {
console.log(`Customer ${i + 1}: ${customers[i]}`)
}Expected result:
Customer 1: Priya
Customer 2: Rana
Customer 3: AnaPlain English breakdown:
customers.length→ how many items are in the array (3)customers[i]→ the item at positioni- Because
i < customers.length, the loop visits every item exactly once
Common mistake: Off-by-one errors. The last index is length - 1, never length. customers[3] on a 3-item array is undefined — array indices start at 0.
Essential commands
| Command / action | What it does |
|---|---|
if (cond) { } else if { } else { } | Branch on a condition |
if (boolVar) { } | Use a boolean directly — no === true |
for (start; cond; step) { } | Loop a known number of times |
while (cond) { } | Loop while a condition stays true |
break | Stop the loop immediately |
continue | Skip the current iteration, move to the next |
array.length | Number of items in the array |
array[i] | The item at position i (0-based) |
Practice
Do this now:
- Create
practice3.js. - Declare
let grades = [72, 88, 55, 91, 64, 80]. - Loop over the array with
forand print each grade asGrade: Xwhere X is"Distinction"(>=80),"Pass"(>=60), or"Fail"(<60). - Use
continueinside the loop to skip the grade55instead of classifying it. - Use
breakif you reach a grade of91(assume a perfect score ends grading early).
Expected output:
Grade 72 — Pass
Grade 88 — Distinction
(Grade 55 skipped)
Grade 91 — DistinctionTest yourself
- You have
if (a) ...andif (a === true) .... What is the difference?
Answer
None — both run when a is true. if (a) is preferred because it is shorter and reads cleaner. The only difference is a === true also rejects truthy values like 1 or "yes", but for a true/false boolean they are identical.
- In the loop
for (let i = 0; i < 5; i++), when does the incrementi++run?
Answer
After the loop body finishes each iteration, before the next condition check. i++ does not run before the first iteration — the first condition check happens with i = 0.
- What happens if you never update the loop variable in a
whileloop?
Answer
The condition stays true forever and the loop never exits — an infinite loop. The script hangs (or in a browser, the tab freezes). Always make sure the body eventually changes the condition in some way.
- You have
let xs = ["a","b","c"]. What doesxs[xs.length]give you?
Answer
xs[3] — the index is out of range, so it returns undefined. Indices run from 0 to length - 1 (2 in this case).
- When should you use
whileinstead offor?
Answer
Use for when you know how many times you will loop. Use while when the number of repeats is unknown and depends on a condition changing as you go — like polling an API until it succeeds or retrying a request a certain number of times.
Summary
Conditionals pick one branch among many. for loops count a known number of repeats; while loops go until a condition flips. break exits a loop early, continue skips one iteration. Iterating arrays is the single most common loop pattern — remember indices start at 0, so the last index is always length - 1.
Verified against ECMAScript 2023 / Node.js LTS documentation, September 2026.