SyntaxPilot
Courses/JavaScript/Lesson 6

JavaScript · Lesson 6 of 40 · 12 min

Loops: for, while, for...of, for...in

queued

These are the notes for JavaScript episode 6. You will learn why copy-pasting code doesn't scale, the four parts of every loop, the while loop, infinite loops, the for loop, off-by-one errors, running totals, for...of over lists and strings, for...in over objects (and why not on arrays), break and continue, nested loops, loop variable scope and do...while. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js).

Why loops: queue tokens at Ravi's stall

Ravi's chai stall has a queue every morning, and his app prints a numbered token for each customer. With what we knew so far, the only way is one console.log per token, copy-pasted:

console.log("Token 1");
console.log("Token 2");
console.log("Token 3");
console.log("Token 4");
console.log("Token 4");
Token 1
Token 2
Token 3
Token 4
Token 4

A pasted line wasn't edited: Token 4 twice, no Token 5. And that's only five customers; on a Sunday there are a hundred. Repeating by hand doesn't scale and breeds typos. We need a way to say: do this again and again until a condition says stop. That is a loop.

The while loop: a bank's token machine

The token machine In JavaScript Part of the loop
Start at token 1 let token = 1; start: a counter
Anyone still waiting? while (token <= 5) condition: checked before every round
Print the token { console.log(...) } body: the job
Next number token++ update: move towards the end
let token = 1;
while (token <= 5) {
  console.log(`Token ${token}`);
  token++;
}
console.log("Queue done");
Token 1
Token 2
Token 3
Token 4
Token 5
Queue done

When token became 6, the condition was false, the loop ended, and the program continued after it. Each round of a loop is called an iteration.

For the Sunday rush, change one number: while (token <= 100). The same five lines now print Token 1 to Token 100, then Queue done. Change one number, not 100 lines.

Infinite loops: a treadmill with no stop button

Forget the update line (token++) and token stays 1 forever. 1 <= 5 is always true, so the loop never ends: Token 1, Token 1, Token 1... This is an infinite loop.

  • In a terminal, stop it with Ctrl + C.
  • Online compilers (including SyntaxPilot's) stop it after a time limit.
  • The fix: make sure every iteration moves the loop towards its stop condition.

The for loop: one over in cricket

In a while loop the start, check and update are scattered over three lines, which is exactly how an update gets forgotten. A for loop keeps all three in one line, separated by semicolons.

One over In JavaScript Part
Start at ball 1 let ball = 1; start
Six balls done yet? ball <= 6; check
Count the next ball ball++ update

Off-by-one: the five-ball over

for (let ball = 1; ball < 6; ball++) {
  console.log(`Ball ${ball}`);
}
Ball 1
Ball 2
Ball 3
Ball 4
Ball 5

An over has six balls! Starting at 1, ball < 6 stops after ball 5. This is an off-by-one error, the most common loop bug.

for (let ball = 1; ball <= 6; ball++) {
  console.log(`Ball ${ball}`);
}
Ball 1
Ball 2
Ball 3
Ball 4
Ball 5
Ball 6

Rule: start at 1 → use <=; start at 0 → use <. Always check the first and the last iteration.

Running total: 1 + 2 + ... + 100

let sum = 0;
for (let i = 1; i <= 100; i++) {
  sum += i;
}
console.log(sum);
5050

Like a cash box: it starts empty (0) and every sale is added in. i (short for index) is the standard name for a loop counter.

Counting down

The update can go down too:

for (let i = 5; i >= 1; i--) {
  console.log(`${i}...`);
}
console.log("Go!");
5...
4...
3...
2...
1...
Go!

Anatomy of a for loop

for (let i = 1;  i <= 6;  i++) { body }
     └ start ┘   └check┘  └update┘
Step When it runs
let i = 1 once, before everything
i <= 6 before every round; false ends the loop
body each round, when the check is true
i++ after every round, then back to the check
Use When
while you don't know how many rounds (until a condition: "read orders until the shop closes")
for you do know how many rounds (6 balls, 100 tokens)

for...of: add up today's orders

A list of values in square brackets is an array (you saw one from split in episode 4; arrays get their own episode next). for...of hands you each value, one by one, like a cashier taking notes off a pile. It also works on strings, one character at a time.

const prices = [120, 80, 250];
let total = 0;
for (const price of prices) {
  total += price;
}
console.log(`Total: Rs ${total}`);
for (const ch of "chai") {
  console.log(ch);
}
Total: Rs 450
c
h
a
i

No counter, no index, no off-by-one possible. The loop variable can be const, because each round gets a fresh one.

The classic counter version also works, using prices.length and prices[i]:

const prices = [120, 80, 250];
for (let i = 0; i < prices.length; i++) {
  console.log(`Order ${i + 1}: Rs ${prices[i]}`);
}
Order 1: Rs 120
Order 2: Rs 80
Order 3: Rs 250

Use the counter version only when you need the position; otherwise for...of is cleaner.

for...in: the "0012" trap

Swap of for in on the same list:

const prices = [120, 80, 250];
let total = 0;
for (const p in prices) {
  total += p;
}
console.log(total);
0012

for...in doesn't give the values: it gives the indexes, as strings:

const prices = [120, 80, 250];
for (const p in prices) {
  console.log(p, typeof p);
}
0 string
1 string
2 string

So 0 + "0" glued into "00", then "001", then "0012". A silent bug from a two-letter difference.

What for...in is really for: the menu card

Ravi's menu card In JavaScript Meaning
A menu card: name → price { chai: 10, samosa: 12 } an object: labels with values
Read each label for (const item in menu) gives each label (key)
Then its price menu[item] the value for that key
const menu = { chai: 10, samosa: 12, vadaPav: 15 };
for (const item in menu) {
  console.log(`${item}: Rs ${menu[item]}`);
}
chai: Rs 10
samosa: Rs 12
vadaPav: Rs 15

Lists → for...of. Objects → for...in. (Objects get their own episode soon.)

break and continue: packing the day's orders

The packing counter In JavaScript Effect
A cancelled order: skip it, take the next continue skip the rest of this round, go to the next
A huge Rs 600 order: stop and call Ravi break leave the loop completely
const orders = [120, 0, 250, 80, 600];
for (const amount of orders) {
  if (amount === 0) {
    continue;
  }
  if (amount >= 500) {
    console.log(`Big order Rs ${amount}! Call Ravi.`);
    break;
  }
  console.log(`Packed Rs ${amount}`);
}
Packed Rs 120
Packed Rs 250
Packed Rs 80
Big order Rs 600! Call Ravi.

The 0 was skipped silently, and the loop stopped at 600. break works the same way it did in switch (episode 5).

Nested loops: rows of seats

A loop inside a loop. The outer loop picks a row; the inner loop goes through every seat in that row.

for (let row = 1; row <= 3; row++) {
  let line = "";
  for (let seat = 1; seat <= 4; seat++) {
    line += `R${row}S${seat} `;
  }
  console.log(line);
}
R1S1 R1S2 R1S3 R1S4 
R2S1 R2S2 R2S3 R2S4 
R3S1 R3S2 R3S3 R3S4 

The inner loop runs completely for every round of the outer loop, like a clock's minute hand going all the way round for every hour: 3 × 4 = 12 iterations of the inner body.

Loop variable scope

A counter declared with let in a for loop exists only inside that loop:

for (let i = 0; i < 3; i++) {
  console.log(i);
}
console.log(i);
0
1
2
ReferenceError: i is not defined

That's a good thing: every loop gets its own fresh counter, and loops can't interfere with each other. If you need the value afterwards, declare the variable before the loop.

do...while: the PIN screen

do...while runs the body first and checks after, so the body always runs at least once, like a PIN screen that must take a PIN before it can check it.

let tries = 0;
let pin;
do {
  tries++;
  pin = tries === 2 ? "4821" : "1111";
  console.log(`Try ${tries}: ${pin}`);
} while (pin !== "4821");
Try 1: 1111
Try 2: 4821

Even when the condition is false from the start, the body runs once:

let n = 10;
do {
  console.log("Runs once, even though n > 5");
} while (n < 5);
Runs once, even though n > 5

Common mistakes (and what really happens)

You wrote What happens Why Fix
while (token <= 5) { ... } with no token++ (no error) runs forever (Ctrl + C / time limit) the condition never becomes false update the counter every round
for (let b = 1; b < 6; b++) (no error) only 5 rounds off-by-one b <= 6
for (const p in prices) total += p; (no error) "0012" for...in gives indexes as strings for (const p of prices)
console.log(i); after for (let i ...) ReferenceError: i is not defined let i lives inside the loop use i inside, or declare it before
let sum; then sum += i (no error) NaN undefined + 1 is NaN start running totals at 0
copy-pasted lines (no error) duplicates / missing values repeating by hand a loop

Mini project: a daily sales report

const orders = [120, 0, 250, 80, 600, 45];  // 0 = cancelled
let total = 0;
let count = 0;
for (const amount of orders) {
  if (amount === 0) {
    continue;
  }
  total += amount;
  count++;
  const bar = "#".repeat(Math.floor(amount / 50));
  console.log(`Rs ${String(amount).padStart(3)} ${bar}`);
}
console.log(`${count} orders, Rs ${total}`);
console.log(`Average: Rs ${Math.round(total / count)}`);
Rs 120 ##
Rs 250 #####
Rs  80 #
Rs 600 ############
Rs  45 
5 orders, Rs 1095
Average: Rs 219
  • continue skips cancelled orders.
  • A running total and a counter, both starting at 0.
  • "#".repeat(n) draws one # per ₹50; padStart(3) lines up the amounts.
  • Math.round rounds the average to the nearest rupee.

Try adding your own orders to the list.

Practice

  1. Print the 7 times table, from 7 x 1 to 7 x 10.
  2. Add all the even numbers from 1 to 100 (the answer is 2550).
  3. Count the vowels in "syntaxpilot" with for...of.
  4. Print a triangle of * with nested loops (4 rows).
Solutions and hints

1.

for (let i = 1; i <= 10; i++) {
  console.log(`7 x ${i} = ${7 * i}`);
}
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
  1. Start at 2 and step by 2:
let sum = 0;
for (let i = 2; i <= 100; i += 2) {
  sum += i;
}
console.log(sum);
2550
  1. includes from episode 4 checks whether the character is a vowel:
let vowels = 0;
for (const ch of "syntaxpilot") {
  if ("aeiou".includes(ch)) {
    vowels++;
  }
}
console.log(vowels);
3
  1. The inner loop runs row times:
for (let row = 1; row <= 4; row++) {
  let line = "";
  for (let s = 1; s <= row; s++) {
    line += "*";
  }
  console.log(line);
}
*
**
***
****

Quick quiz

How many times does "Hi" print?

for (let i = 0; i <= 10; i += 2) {
  console.log("Hi");
}
  • A. 5
  • B. 6
  • C. 10
  • D. 11
Answer

B. i takes the values 0, 2, 4, 6, 8, 10: six values, because <= 10 includes 10. Then i becomes 12 and the check fails.

Interview questions

  • What are the parts of a loop? What happens if the update is missing?
  • What's the difference between while and do...while?
  • When would you choose while over for?
  • What is an off-by-one error? How do you avoid it?
  • What's the difference between for...of and for...in? Why shouldn't you use for...in on arrays?
  • What do break and continue do?
  • How many times does the inner body of a nested loop run for loops of size m and n?
  • Why is i not available after for (let i = 0; ...)?

Glossary

Term Meaning Example
Loop code that repeats while a condition is true while (token <= 5) { ... }
Iteration one round of a loop printing Token 3
Counter a variable that counts the rounds let token = 1
Condition the true/false check before each round token <= 5
Body the block of code repeated each round { console.log(...) }
Update the step that moves the counter token++
while loop repeats while a condition is true while (x < 10) { ... }
for loop start, check and update in one line for (let i = 1; i <= 6; i++)
Infinite loop a loop whose condition never becomes false no token++
Off-by-one error a loop that runs one time too many or too few ball < 6 from 1
Running total a sum built up one value at a time, starting at 0 sum += i
Array a list of values in square brackets [120, 80, 250]
for...of loops over each value of a list or string for (const p of prices)
Object labelled values in curly brackets { chai: 10, samosa: 12 }
Key a label in an object chai
for...in loops over each key of an object for (const item in menu)
break leave the loop completely stop at a ₹600 order
continue skip the rest of this round skip cancelled orders
Nested loop a loop inside another loop rows × seats
Scope where a variable exists let i only inside its loop
do...while body first, check after: runs at least once a PIN screen
repeat a string method that repeats text n times "#".repeat(3) → "###"

Summary

  • Every loop has a start, a check, a body and an update. No update → infinite loop.
  • while repeats until a condition fails; for keeps start, check and update in one line.
  • Watch off-by-one: start at 1 → <=; start at 0 → <. Running totals start at 0.
  • for...of gives each value (lists, strings); for...in gives each key (objects). Never for...in on arrays.
  • break stops the loop; continue skips one round.
  • Nested loops run the inner loop fully for every outer round; let i lives only inside its loop; do...while runs at least once.

Next episode: arrays and array methods. Ravi wants to add, remove, sort and search his orders, so you'll master arrays.