Rana Maninder Singh
Lesson 3 of 9JavaScript Basics

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

ResourceLink
PreviousVariables, types & operators
NextFunctions & scope
Time~25 minutes

What you will learn

  • if/else if/else — telling the program which branch to run
  • for and while — repeating code a set number of times (or until a condition changes)
  • break and continue — 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:

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: 4

Plain English breakdown of ONE iteration:

  1. let i = 0 → runs once at the very start
  2. i < 5 → checked before every iteration
  3. run the block
  4. i++ → runs after the block, adds 1 to i
  5. back to step 2 — until i < 5 is 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 3

Common 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

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
7

Plain 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: Ana

Plain English breakdown:

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 / actionWhat 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
breakStop the loop immediately
continueSkip the current iteration, move to the next
array.lengthNumber of items in the array
array[i]The item at position i (0-based)

Practice

Do this now:

  1. Create practice3.js.
  2. Declare let grades = [72, 88, 55, 91, 64, 80].
  3. Loop over the array with for and print each grade as Grade: X where X is "Distinction" (>=80), "Pass" (>=60), or "Fail" (<60).
  4. Use continue inside the loop to skip the grade 55 instead of classifying it.
  5. Use break if you reach a grade of 91 (assume a perfect score ends grading early).

Expected output:

Grade 72 — Pass
Grade 88 — Distinction
(Grade 55 skipped)
Grade 91 — Distinction

Test yourself

  1. You have if (a) ... and if (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.

  1. In the loop for (let i = 0; i < 5; i++), when does the increment i++ 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.

  1. What happens if you never update the loop variable in a while loop?
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.

  1. You have let xs = ["a","b","c"]. What does xs[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).

  1. When should you use while instead of for?
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.