Skip to content
HopperHopper

Course navigation

Phase 1 · FoundationsDay 5

Loops

  • About 75 minutes
  • 10 sections
  • Runnable TypeScript examples
  • Practice questions

Before you start

About 75 minutes

By the end you will be able to

  1. Write a while loop that stops when it should, and recognize and fix an infinite loop.
  2. Choose between a counting for loop, for...of over a string, and while, and say why.
  3. Use break to leave a loop early and continue to skip one pass.
  4. Count, sum, and find a largest or smallest value with an accumulator, and build a grid with nested loops.

What to remember from earlier

Section 1 of 10

5.1 Repeating with while

Before you start, set up a new project folder named day05 exactly as you set up day01 in 1.2: open the folder in VS Code, run npm init -y and npm install --save-dev typescript in its terminal, and type the same tsconfig.json. Every program today goes in that folder.

Every statement you have written so far runs at most once. Day 4 let the program skip a block, but nothing has ever made it repeat one. To count down from 3, you could write three console.log lines. To count down from 1000, or to keep doubling a sum until it reaches a target, copying lines is hopeless. Programs need a way to run the same block again and again, and to know when to stop.

A loop is a statement that runs a block repeatedly. Each run of the block is called an iteration, or a pass. The simplest loop is the while loop, which looks a lot like Day 4’s if:

while (condition) {
  statements that run again and again, as long as the condition is true
}
Piece What it is
while The keyword that starts the loop
(condition) The loop condition: any expression that gives true or false, checked before every pass
{ and } The loop body: the block that runs on each pass, as long as the condition is true

When the program reaches the while, it works out the condition. If it is true, the body runs once, top to bottom, and then the program goes back to the condition and checks it again. If it is true again, the body runs again. This continues until a check gives false; then the whole loop is skipped and the program carries on after the closing }. The difference from if is that one word: an if runs its block at most once, while a while keeps going back.

For the loop to end, something in the body must change what the condition looks at. Usually that is a variable that the body updates on every pass, the way Day 2’s score = score + 5 updated a let.

Worked example: A countdown

Follow count through every check of the condition.

countdown.ts
let count = 3;
while (count > 0) {
  console.log(count);
  count = count - 1;
}
console.log("Liftoff!");
3
2
1
Liftoff!
Check of count > 0 Result Body runs? count after the body
3 > 0 true Yes: shows 3 2
2 > 0 true Yes: shows 2 1
1 > 0 true Yes: shows 1 0
0 > 0 false No: loop ends

Line 1 makes count with a let, because the body is going to change it. The condition on line 2 is checked four times: three checks pass and the body runs three times; the fourth check fails, and the program jumps from line 2 to line 6. Line 4 is what makes the loop end. It subtracts 1 every pass, so the condition must eventually become false.

Now vary the starting value, and nothing else. Set count to 0:

countdown-zero.ts
let count = 0;
while (count > 0) {
  console.log(count);
  count = count - 1;
}
console.log("Liftoff!");
Liftoff!

The very first check, 0 > 0, is false, so the body never runs at all, and the program goes straight to the last line. A while loop checks before each pass, including the first one, so its body can run zero times. Keep that in mind when a loop seems to “do nothing”: its condition may have been false from the start.

The countdown always runs three times, which you could count before running it. The real power of while shows when nobody knows in advance how many passes it will take. Suppose you have $15 and it doubles every week: how many weeks until you have at least $100?

savings.ts
let savings = 15;
let weeks = 0;
while (savings < 100) {
  savings = savings * 2;
  weeks = weeks + 1;
}
console.log(weeks, savings);
3 120
Check of savings < 100 Result savings after weeks after
15 < 100 true 30 1
30 < 100 true 60 2
60 < 100 true 120 3
120 < 100 false

Nothing in the program says “three”: the loop found that out by trying. The body updates two variables, and only one of them, savings, is in the condition; weeks just keeps count. Line 7 runs once, after the loop, when both variables hold their final values.

Key idea

while (condition) { ... } checks the condition, runs the body if it is true, and goes back to check again, until a check gives false. The body can run zero times. Something in the body must change the condition’s answer, or the loop never ends.

Watch out

Forgetting to change the condition. Leave out line 4 of the countdown, and the condition never changes:

let count = 3;
while (count > 0) {
  console.log(count);
}

3 > 0 is true, the body shows 3, the check is 3 > 0 again, and so on. A loop whose condition never becomes false is an infinite loop. npx tsc has no complaint: the types are all fine. node shows 3 over and over, as fast as the terminal can draw it, and never stops on its own. When that happens, click in the terminal and press Ctrl+C (on every system, including Mac), which stops the running program. Then find the line that was supposed to change the condition, and add or fix it.

An update that moves the wrong way does the same thing. With count = count + 1 on line 4, count goes 3, 4, 5, … and is always above 0. Before you run any while loop, ask: which variable is in the condition, where does the body change it, and does that change bring the condition closer to false?

Pause and try

Question 1 · Tracing

Predict exactly what this program shows, and how many times the body runs.

halving.ts
let amount = 1000;
let halvings = 0;
while (amount >= 1) {
  amount = amount / 2;
  halvings = halvings + 1;
}
console.log(`${halvings} halvings leave ${amount}`);
Check your reasoning
10 halvings leave 0.9765625

The body runs ten times. Each pass halves amount and adds 1 to halvings:

Pass amount after Pass amount after
1 500 6 15.625
2 250 7 7.8125
3 125 8 3.90625
4 62.5 9 1.953125
5 31.25 10 0.9765625

After the tenth pass, 0.9765625 >= 1 is false, so the loop ends and line 7 shows both values. Dividing by 2 gives exact results here, so the decimals are not a Day 2 float surprise; halving a whole number only ever adds one binary digit.

Reread 5.1 Repeating with while if your count differed.

Question 2 · Multiple choice

A program contains let tries = 5; followed by while (tries > 10) { console.log(tries); tries = tries - 1; }. What happens when it runs?

  1. It shows 5, 4, 3, 2, 1
  2. It shows nothing from the loop, because the first check is already false
  3. It never ends, because tries never reaches 10
  4. npx tsc rejects it, because the condition can never be true
Check your reasoning

B. A while loop checks its condition before the first pass. 5 > 10 is false, so the body never runs and the program carries on after the loop.

  • A is what the loop would show with the condition tries > 0.
  • C is wrong: an infinite loop needs a condition that stays true; this one is false from the start.
  • D is wrong: the checker only checks types. tries is a number, and number > number is fine; unlike Day 4’s TS2367, where the types themselves could never match, nothing here is impossible as far as types go. The checker does not work out what value tries will hold.

Reread 5.1 Repeating with while if you chose differently.

Section 2 of 10

5.2 Updating a Variable in One Step

Every loop body so far has a line like count = count - 1 or weeks = weeks + 1. Loops update variables so often that JavaScript has shorter ways to write “change this variable by this much.” You will use them in nearly every loop from now on, so learn them before the next kind of loop, which puts one in its header.

The compound assignment operators combine an arithmetic operator with =. Each one works out the right side, applies the operator to the variable’s current value, and stores the result back:

Shorthand Means With score at 10
score += 5; score = score + 5; 15
score -= 3; score = score - 3; 7
score *= 2; score = score * 2; 20
score /= 4; score = score / 4; 2.5

Adding or subtracting exactly 1 is so common that it has its own operators. lives++ is the increment operator: it adds 1 to lives. lives-- is the decrement operator: it subtracts 1. Each is a complete statement on its own line, with no = at all.

Worked example: Three ways to change a variable

compound.ts
let score = 10;
score += 5;
console.log(score);
score -= 3;
console.log(score);
score *= 2;
console.log(score);

let lives = 3;
lives++;
console.log(lives);
lives--;
lives--;
console.log(lives);

let laugh = "ha";
laugh += "ha";
console.log(laugh);
15
12
24
4
2
haha
Line Statement Worked out Value after
2 score += 5; 10 + 5 15
4 score -= 3; 15 - 3 12
6 score *= 2; 12 * 2 24
10 lives++; 3 + 1 4
12 lives--; 4 - 1 3
13 lives--; 3 - 1 2
17 laugh += "ha" "ha" + "ha" "haha"

Each shorthand reads the current value, changes it, and stores the result, exactly as the long form would. Line 17 shows that += follows the same rules as +: with a string on the left, it joins, as in 3.2. There is no ++ for strings, because “add 1” means nothing for text.

You may see ++ used inside a larger expression elsewhere, such as console.log(lives++), where it has a value as well as an effect; the value is surprising (the old one), so this course always writes ++ and -- as statements of their own, and so should you.

Key idea

x += n, x -= n, x *= n, and x /= n change x by n in place. x++ adds 1 and x-- subtracts 1. Each one reads the current value, changes it, and stores the result, so the variable must be a let.

Watch out

Updating a constant, or changing a variable’s type. The shorthands assign, so every rule about assignment still applies:

compound-wrong.ts
const total = 0;
total += 5;
let lives = 3;
lives += "1";
compound-wrong.ts:2:1 - error TS2588: Cannot assign to 'total' because it is a constant.
compound-wrong.ts:4:1 - error TS2322: Type 'string' is not assignable to type 'number'.

Line 2 is Day 2’s TS2588: total += 5 means total = total + 5, and a const can never be assigned again. Declare a variable that a loop will update with let. Line 4 is Day 1’s TS2322: lives + "1" would join a number to a string and give the string "31", and a number variable cannot hold a string, as 2.6 explained. Without the checker, node would quietly turn lives into text. Write lives += 1, or lives++. Fix or delete the file before your next check.

Pause and try

Question 3 · Tracing

Predict exactly what this program shows.

predict-update.ts
let points = 4;
points *= 3;
points -= 2;
points++;
let label = "Level ";
label += points;
console.log(points);
console.log(label);
Check your reasoning
11
Level 11
Line Statement points after
2 points *= 3; 12
3 points -= 2; 10
4 points++; 11

Line 6 is label = label + points. The left side is a string, so + joins: "Level " + 11 is "Level 11", and label stays a string, which the checker allows. Joining a number onto a string is fine; it was a string onto a number, in compound-wrong.ts, that was not.

Reread 5.2 Updating a Variable in One Step if any line differed.

Section 3 of 10

5.3 Counting with for

Look at countdown.ts again. Three separate lines manage the counting: line 1 starts count at 3, line 2 checks it, and line 4 changes it. They belong together, but they are spread over the program, and it is easy to forget one, as the Watch Out in 5.1 showed. When a loop counts, JavaScript has a loop that keeps all three parts in one place: the for loop.

for (start; condition; update) {
  body
}
Piece What it is
start Runs once, before anything else; usually declares the loop variable with let
condition Checked before every pass, exactly as in while; the loop ends when it is false
update Runs after every pass, before the next check; usually i++ or i--
body The block that runs on each pass

The three parts are separated by semicolons inside the parentheses, and the order of events is: start, then check, body, update, check, body, update, … until a check is false. The loop variable is the variable the for counts with. By tradition it is often called i, but any name is allowed, and a longer name such as count or minutes is clearer when the number means something.

Worked example: Counting up to five

count-up.ts
for (let i = 1; i <= 5; i++) {
  console.log(i);
}
console.log("Done");
1
2
3
4
5
Done
Step i Check i <= 5 What happens
Start: let i = 1 1 i is made once
Pass 1 1 true Shows 1, then i++
Pass 2 2 true Shows 2, then i++
Pass 3 3 true Shows 3, then i++
Pass 4 4 true Shows 4, then i++
Pass 5 5 true Shows 5, then i++
Final check 6 false Loop ends; shows Done

The condition is checked six times and the body runs five. After the fifth pass, the update makes i 6, the check 6 <= 5 fails, and the program carries on at line 4. The update on line 1 is the same i++ from 5.2, just written inside the header.

Here is the 5.1 countdown as a for loop. Compare it line by line with countdown.ts:

countdown-for.ts
for (let count = 3; count > 0; count--) {
  console.log(count);
}
console.log("Liftoff!");
3
2
1
Liftoff!

The let count = 3, the count > 0, and the count-- are the same three parts, moved into the header. Both programs do exactly the same thing; the for just makes it impossible to forget the update.

The update does not have to be 1 either way, and the condition can be any comparison. Count in steps of 5:

steps.ts
for (let minutes = 0; minutes <= 20; minutes += 5) {
  console.log(`${minutes} minutes`);
}
0 minutes
5 minutes
10 minutes
15 minutes
20 minutes

minutes += 5 is 5.2’s compound assignment. The check minutes <= 20 includes 20, because <= includes the end. Now count down by two, stopping above zero:

count-down-by-two.ts
for (let n = 10; n > 0; n -= 2) {
  console.log(n);
}
10
8
6
4
2

After 2 the update makes n 0, and 0 > 0 is false. Whenever you write a for header, ask the three questions from 5.1 of its three parts: where does it start, when does it stop, and does each update move toward stopping?

One for shape comes up more than any other: “do this times times.”

repeat-n.ts
const times: number = 3;
for (let i = 0; i < times; i++) {
  console.log(`Pass ${i}`);
}
Pass 0
Pass 1
Pass 2

Starting at 0 and checking i < times runs the body exactly times times, with i going 0, 1, 2. Programmers start at 0 and use < out of habit, because 5.4 shows that this shape matches the way indexes work. Starting at 1 with i <= times runs the same number of passes, with i going 1, 2, 3; use that when the number is shown to a person, as in count-up.ts.

So which loop should you use? A for loop when you know, or can calculate, how many passes there will be: a count, a number of repeats, a range of numbers. A while loop when the loop runs until something happens and nobody knows how many passes that takes, like the doubling savings.

Key idea

for (start; condition; update) { ... } runs start once, then repeats “check, body, update” until the check is false. Use for when the number of passes is known and while when the loop runs until something happens.

Watch out

Declaring the loop variable with const. Day 2 said to prefer const, but the update changes the loop variable on every pass:

const-counter.ts
for (const lap = 1; lap <= 4; lap++) {
  console.log(`Lap ${lap}`);
}
const-counter.ts:1:31 - error TS2588: Cannot assign to 'lap' because it is a constant.

Column 31 is lap++, the update, which assigns to lap. The loop variable of a counting for is always a let:

const-counter-fixed.ts
for (let lap = 1; lap <= 4; lap++) {
  console.log(`Lap ${lap}`);
}
Lap 1
Lap 2
Lap 3
Lap 4

Using the loop variable after the loop. The header’s let belongs to the loop, in the same way that a variable declared inside an if block belonged to that block in 4.6:

loop-scope.ts
for (let i = 0; i < 3; i++) {
  console.log(i);
}
console.log(`The loop ran ${i} times`);
loop-scope.ts:4:29 - error TS2304: Cannot find name 'i'.

The scope of i is the for statement: its header and its body. After the closing } the name is gone, so line 4 gets Day 1’s TS2304. If you need a count after the loop, declare a separate let before the loop and update it inside, as weeks was in savings.ts. Fix or delete both files before your next check.

Pause and try

Question 4 · Tracing

Predict exactly what this program shows. Each loop has its own header; work out each one’s start, stop, and step.

predict-for.ts
for (let n = 2; n < 10; n += 3) {
  console.log(n);
}
for (let n = 9; n >= 5; n -= 2) {
  console.log(n);
}
Check your reasoning
2
5
8
9
7
5
  • First loop: n starts at 2 and goes up by 3 while it is below 10: 2, 5, 8. After 8 the update makes it 11, and 11 < 10 is false.
  • Second loop: n starts at 9 and goes down by 2 while it is at least 5: 9, 7, 5. After 5 the update makes it 3, and 3 >= 5 is false.

Both loops declare a variable called n, and that is allowed: each let in a for header belongs to its own loop, so the second n is a new variable, made after the first one is gone.

Reread 5.3 Counting with for if any line differed.

Question 5 · Multiple choice

How many times does the body of for (let i = 0; i < 4; i++) { ... } run, and what is i on the last pass?

  1. 4 times; i is 3 on the last pass
  2. 4 times; i is 4 on the last pass
  3. 5 times; i is 4 on the last pass
  4. 3 times; i is 3 on the last pass
Check your reasoning

A. i goes 0, 1, 2, 3, which is four passes. After the pass with i at 3, the update makes i 4, and 4 < 4 is false, so the body never runs with i at 4.

  • B is wrong: the check 4 < 4 fails, so there is no pass with i at 4.
  • C is wrong: there are five checks (0, 1, 2, 3, and the failing 4), but only four passes.
  • D is wrong: this forgets the pass with i at 0. Starting at 0 and stopping below 4 gives 4 passes, not 3.

Reread 5.3 Counting with for if you chose differently.

Section 4 of 10

5.4 Visiting Every Index

On Day 3 you read one character at a time with word[0], word[1], and so on, typing a line for each. The indexes of a string are exactly the numbers a counting for makes: 0, 1, 2, up to length - 1, as 3.4 explained. So a for loop that counts from 0 while i < word.length visits every character, whatever the string’s length.

Worked example: Every index and its character

indexes.ts
const word: string = "code";
for (let i = 0; i < word.length; i++) {
  console.log(i, word[i]);
}
0 c
1 o
2 d
3 e

"code" has length 4, so the condition is i < 4, and i goes 0, 1, 2, 3. On each pass, word[i] reads the character at the current index. The loop never names the number 4: change word to "loops" and the same header visits five characters. That is why this header is written with word.length and not a number.

This loop gives you two things on every pass: the character, word[i], and where it is, i. The position matters whenever a result needs to say “the third character” or “day 2”; 5.9 uses it to report which day was the wettest.

Key idea

for (let i = 0; i < text.length; i++) visits every index of text, from 0 to length - 1, and text[i] reads the character at each one.

Watch out

Running one index too far. With <= instead of <, the loop makes one extra pass:

indexes-off-by-one.ts
const word: string = "code";
for (let i = 0; i <= word.length; i++) {
  console.log(i, word[i]);
}
0 c
1 o
2 d
3 e
4 undefined

The last index of "code" is 3, but 4 <= 4 is true, so there is a pass with i at 4, and word[4] is past the end. Day 3 showed that indexing past the end gives undefined, with no error from the checker or from node. A loop that runs one pass too many or too few is called an off-by-one error. It is the most common loop bug, and it is silent, so check the boundary of every loop by asking what the loop variable is on the first pass and on the last.

Pause and try

Question 6 · Multiple choice

Which header visits every index of name, and no others?

  1. for (let i = 1; i <= name.length; i++)
  2. for (let i = 0; i <= name.length; i++)
  3. for (let i = 0; i < name.length; i++)
  4. for (let i = 0; i < name.length - 1; i++)
Check your reasoning

C. Indexes run from 0 to length - 1, which is exactly the numbers from 0 while i < name.length.

  • A is wrong: it skips index 0, the first character, and its last pass reads name[name.length], which is undefined.
  • B is wrong: it starts right, but <= adds a pass at name.length, past the end.
  • D is wrong: i < name.length - 1 stops one early, so the last character is never visited.

Reread 5.4 Visiting Every Index if you chose differently.

Section 5 of 10

5.5 for…of Over a String

In indexes.ts, the index i was shown, so it earned its place. But often you want only the characters: shout each letter of a name, count the vowels, drop the spaces. Then the counting header is noise, and it is a place for an off-by-one slip. For “do this with each character,” JavaScript has a second kind of for: the for...of loop.

for (const item of text) {
  body
}
Piece What it is
const item A new variable, made fresh on each pass and holding the current character
of The keyword that says “take each item of”
text The string to walk through, from its first character to its last

There is no condition and no update: the loop ends by itself after the last character. And the variable is a const, not a let. That looks odd next to 5.3, but it is right: nothing in the header assigns to item. The loop makes a new item for every pass, holding the next character, and your body never has to change it. (A let is allowed here, but const says what you mean.)

Worked example: Spelling a word

spell.ts
const word: string = "loop";
for (const letter of word) {
  console.log(letter);
}
console.log("Done");
l
o
o
p
Done
Pass letter Shows
1 "l" l
2 "o" o
3 "o" o
4 "p" p

Hover over letter in VS Code and it shows const letter: string: each character comes out as a string of length 1, so every string method works on it. After the fourth pass there are no characters left, the loop ends, and line 5 runs.

Now vary the body: use a method on each character, and the whole string after the loop.

cheer.ts
const team: string = "Ana";
for (const letter of team) {
  console.log(`Give me ${letter.toUpperCase()}!`);
}
console.log(`What does that spell? ${team}!`);
Give me A!
Give me N!
Give me A!
What does that spell? Ana!

letter.toUpperCase() makes a capital copy of each character, as on Day 3; team itself is unchanged, because strings are immutable, so line 5 still shows Ana. Every character is visited, including repeats: the two as each get a pass.

When should you use which for? Use for...of when the body needs only each character. Use the counting for from 5.4 when the body needs the index too, or when the loop is counting numbers rather than walking through text.

Key idea

for (const ch of text) { ... } runs the body once per character, first to last, with ch holding the current one. Use it when you need the characters and not their positions.

Watch out

Writing in instead of of. JavaScript also has a for...in loop, one letter different. It is for a kind of value that Day 7 introduces, not for strings, and the checker says so:

for-in.ts
const word: string = "loop";
for (const letter in word) {
  console.log(letter);
}
for-in.ts:2:22 - error TS2407: The right-hand side of a 'for...in' statement must be of type 'any', an object type or a type parameter, but here has type 'string'.

Column 22 is word, the thing after in. Run with node anyway, for...in would give you the indexes as strings, "0", "1", and so on, not the characters, which is rarely what anyone wants. With a string after it, the keyword is always of. Fix or delete the file before your next check.

Pause and try

Question 7 · Tracing

Predict exactly what this program shows. Count the lines.

brackets.ts
for (const ch of "a b!") {
  console.log(`[${ch}]`);
}
Check your reasoning
[a]
[ ]
[b]
[!]

Four lines, one per character. A space and an exclamation mark are characters like any other, so for...of visits them too; the second line is a space between brackets. The string can be written straight after of, with no variable, because of takes any string.

Reread 5.5 for…of Over a String if your output differed.

Question 8 · Multiple choice

Why is const correct for letter in for (const letter of word), when the loop variable in for (let i = 0; ...) had to be let?

  1. Because for...of loops run only once
  2. Because a counting for assigns to its variable in the update, while for...of makes a new variable for each pass and never assigns to it
  3. Because strings are immutable, so the variable cannot change
  4. Because const is faster
Check your reasoning

B. i++ is an assignment, and a const cannot be assigned, so the counting loop needs let. A for...of loop makes a fresh letter on every pass that holds the next character; nothing ever assigns to an existing letter, so const is allowed and says that the body does not change it.

  • A is wrong: for...of runs once per character; spell.ts ran four times.
  • C is wrong: the string being immutable is about the string, not the variable. A let would also be allowed here.
  • D is wrong: const is about meaning, not speed.

Reread 5.5 for…of Over a String if you chose differently.

Section 6 of 10

5.6 Leaving a Loop Early with break

A loop that searches for something has no reason to keep going once it has found it. Looking for the first digit in a code, you want to stop at the digit, not visit every character after it. You met the keyword for this on Day 4: in 4.10, break left a switch. Inside a loop, break ends the loop at once, whatever the condition says, and the program carries on after the loop’s closing }. Any statements left in the body for that pass are skipped, and there are no more passes.

Worked example: The first digit in a code

first-digit.ts
const code: string = "AB7C9";
for (const ch of code) {
  if ("0123456789".includes(ch)) {
    console.log(`First digit: ${ch}`);
    break;
  }
  console.log(`Not a digit: ${ch}`);
}
console.log("Search over");
Not a digit: A
Not a digit: B
First digit: 7
Search over
Pass ch "0123456789".includes(ch) What happens
1 "A" false Skips the if; line 7 shows Not a digit: A
2 "B" false Line 7 shows Not a digit: B
3 "7" true Line 4 shows First digit: 7; line 5 break ends the loop

Line 3 uses Day 3’s includes the other way round from usual: instead of asking whether the code contains a digit, it asks whether the string of all ten digits contains ch, which is a neat way to ask “is this character a digit?”. On the third pass the if block runs, and its break leaves the loop: line 7 does not run for "7", the characters C and 9 are never visited, and the program goes to line 9.

Often the program needs to know after the loop whether the search succeeded. The loop above only prints; a program that must decide something later needs to record the result. The usual way is a boolean variable, called a flag, that starts as false and is set to true when the thing is found:

has-digit.ts
const password: string = "sunshine";
let hasDigit = false;
for (const ch of password) {
  if ("0123456789".includes(ch)) {
    hasDigit = true;
    break;
  }
}
if (hasDigit) {
  console.log("Has a digit.");
} else {
  console.log("No digits: add one to make it stronger.");
}
No digits: add one to make it stronger.

hasDigit is declared before the loop, so it is still in scope after it. The loop sets it to true and breaks as soon as a digit appears. For "sunshine" no character is a digit, the loop visits all eight characters, the flag is still false, and the else block runs. Change the password to "sun5hine" and the loop stops at the 5 with the flag true.

Now vary it: sometimes the natural condition is “stop when this happens,” with no condition at the top at all. Then write while (true), whose condition is always true, and put the stopping test inside with break:

smallest-square.ts
let n = 1;
while (true) {
  if (n * n > 50) {
    break;
  }
  n++;
}
console.log(`${n} is the smallest number whose square is over 50`);
8 is the smallest number whose square is over 50

n goes 1, 2, 3, … and each pass tests n * n > 50. For 7 the square is 49, not over 50, so n++ runs; for 8 it is 64, the break runs, and n is still 8 when line 8 shows it. A while (true) loop must contain a break that the program will reach, or it is an infinite loop on purpose.

Key idea

break ends the loop at once and the program carries on after the loop’s }. Use it to stop a search when the answer is found, with a flag variable declared before the loop when you need the result afterwards.

Watch out

Expecting break to stop the program. break leaves a loop or a switch, nothing else. Outside both, the checker refuses it:

break-outside.ts
const balance: number = -20;
if (balance < 0) {
  console.log("Account overdrawn");
  break;
}
console.log("Balance checked");
break-outside.ts:4:3 - error TS1105: A 'break' statement can only be used within an enclosing iteration or switch statement.

“Iteration statement” is the checker’s name for a loop. The if on line 2 is inside neither, so there is nothing for break to leave. There is no statement for “stop the program here” in this course; a program ends when it runs out of statements, so use if and else to choose what runs, and delete the break. Fix or delete the file before your next check.

Pause and try

Question 9 · Tracing

Predict exactly what this program shows.

predict-break.ts
const word: string = "banana";
let seen = "";
for (const ch of word) {
  if (ch === "n") {
    break;
  }
  seen += ch;
}
console.log(seen);
console.log("Done");
Check your reasoning
ba
Done
Pass ch ch === "n" seen after
1 "b" false "b"
2 "a" false "ba"
3 "n" true break

On the third pass the if block runs and break ends the loop before line 7 can add the n. The remaining characters are never visited. seen was declared before the loop, so line 9 can still show it, and line 10 runs as normal: break leaves the loop, not the program.

Reread 5.6 Leaving a Loop Early with break if any line differed.

Section 7 of 10

5.7 Skipping One Pass with continue

Sometimes you do not want to stop the loop, only to skip the rest of the body for this character or number, and go straight on to the next one. Printing the letters of "a b c" in capitals, you want to pass over each space and carry on. The keyword for that is continue: it ends the current pass immediately and the loop goes on to the next one.

Worked example: Skipping the spaces

skip-spaces.ts
const letters: string = "a b c";
for (const ch of letters) {
  if (ch === " ") {
    continue;
  }
  console.log(ch.toUpperCase());
}
console.log("Done");
A
B
C
Done
Pass ch ch === " " What happens
1 "a" false Line 6 shows A
2 " " true continue: line 6 is skipped
3 "b" false Line 6 shows B
4 " " true continue: line 6 is skipped
5 "c" false Line 6 shows C

On passes 2 and 4, continue jumps from line 4 straight to the next pass, so line 6 never runs for a space. Unlike break, the loop is not over: it moves on to the next character, and all five characters are visited.

In a counting for, “the next pass” means the update runs, then the condition is checked. Skip every multiple of 3:

skip-threes.ts
for (let n = 1; n <= 7; n++) {
  if (n % 3 === 0) {
    continue;
  }
  console.log(n);
}
1
2
4
5
7

For 3 and 6, n % 3 === 0 is true, continue skips line 5, and the header’s n++ still runs, so the loop reaches 4 and 7. Because the update is in the header, a counting for cannot get stuck on a continue.

A while loop is different: continue jumps straight to the condition, and nothing in the header updates anything. So in a while, the update must come before the continue:

skip-three-while.ts
let n = 0;
while (n < 5) {
  n++;
  if (n === 3) {
    continue;
  }
  console.log(n);
}
1
2
4
5

Line 3 moves n on first, and only then does line 4 test it. When n is 3, continue goes back to the check 3 < 5, which is true, and the next pass makes n 4. Two keywords, two different jumps:

Keyword What it ends Where the program goes next
break The whole loop The statement after the loop’s }
continue The current pass The update (in for), then the next check

You can always write a loop without continue: skip-spaces.ts could say if (ch !== " ") { console.log(ch.toUpperCase()); } instead. continue earns its place when the body is long and the “skip this one” test belongs at the top, as in this day’s Putting it together.

Key idea

continue ends the current pass and goes on to the next one: in a for, the update still runs; in a while, the program jumps straight back to the condition, so update the variable before the continue.

Watch out

continue before the update in a while. Move line 3 of skip-three-while.ts to the end of the body:

let n = 0;
while (n < 5) {
  if (n === 3) {
    continue;
  }
  console.log(n);
  n++;
}

This shows 0, 1, 2, and then stops showing anything, but does not end. When n is 3, continue jumps to the condition, 3 < 5 is true, the if is true again, and n++ at the end of the body is never reached: an infinite loop that prints nothing, which is harder to notice than one that fills the terminal. Press Ctrl+C, and move the update above the continue.

Pause and try

Question 10 · Tracing

Predict exactly what this program shows. Watch where n++ is.

skip-multiples.ts
let n = 0;
let total = 0;
while (n < 6) {
  n++;
  if (n % 3 === 0) {
    continue;
  }
  total += n;
}
console.log(n, total);
Check your reasoning
6 12
n after line 4 n % 3 === 0 total after
1 false 1
2 false 3
3 true 3 (skipped)
4 false 7
5 false 12
6 true 12 (skipped)

After the pass with n at 6, the check 6 < 6 is false and the loop ends. n is 6 and total is 1 + 2 + 4 + 5, which is 12. Because n++ comes before the continue, the multiples of 3 are skipped without getting stuck.

Reread 5.7 Skipping One Pass with continue if your output differed.

Question 11 · Tracing

Predict exactly what this program shows. It uses both keywords.

no-way.ts
const typed: string = "no-way!out";
let result = "";
for (const ch of typed) {
  if (ch === "!") {
    break;
  }
  if (ch === "-") {
    continue;
  }
  result += ch;
}
console.log(result);
Check your reasoning
noway

The characters are visited in order: n, o are added; - meets continue, so line 10 is skipped and the loop goes on; w, a, y are added; ! meets break, so the loop ends and o, u, t are never visited. result is "noway". The - was skipped but the loop went on; the ! stopped it for good.

Reread 5.7 Skipping One Pass with continue and 5.6 Leaving a Loop Early with break if your output differed.

Section 8 of 10

5.8 Accumulators: Counting and Summing

What is 1 + 2 + 3 + … + 100? A loop can visit every number from 1 to 100, but each pass sees only one number, and when the pass ends, the loop variable moves on. To add them up, the program needs a variable that lives outside the loop and collects a result across all the passes.

Such a variable is called an accumulator. The pattern is always the same three steps:

  1. Before the loop, declare it with let and a starting value that means “nothing collected yet.”
  2. Inside the loop, update it on each pass, usually with 5.2’s += or ++.
  3. After the loop, use the finished result.

You have already seen one: weeks in savings.ts counted the passes. Here it is for a sum:

Worked example: Adding up 1 to 100

sum-to-100.ts
let total = 0;
for (let n = 1; n <= 100; n++) {
  total += n;
}
console.log(`Sum: ${total}`);
Sum: 5050
Pass n total += n total after
1 1 0 + 1 1
2 2 1 + 2 3
3 3 3 + 3 6
4 4 6 + 4 10
… … … …
100 100 4950 + 100 5050

total starts at 0, because adding nothing leaves a sum unchanged. Each pass adds the current n to whatever has been collected so far. After the hundredth pass the loop ends, and line 5 shows the finished sum. Change 100 to 1000 and the same four lines add a thousand numbers.

Now vary what is collected. To count how many characters pass a test, start at 0 and add 1 only when the test is true:

count-vowels.ts
const sentence: string = "TypeScript checks loops too";
let vowels = 0;
for (const ch of sentence.toLowerCase()) {
  if ("aeiou".includes(ch)) {
    vowels++;
  }
}
console.log(`Vowels: ${vowels}`);
Vowels: 7

The if decides whether this pass counts; vowels++ runs for e, i, e, o, o, o, o, and the other characters leave the count unchanged. The loop walks through sentence.toLowerCase(), a lowercase copy, so a capital vowel would count too. To build a string, start with "", the empty string, and join a piece on each pass:

no-spaces.ts
const message: string = "see you soon";
let result = "";
for (const ch of message) {
  if (ch !== " ") {
    result += ch;
  }
}
console.log(result);
seeyousoon

result += ch is Day 3’s joining with +. Every character except the spaces is joined onto the end, and result grows from "" to "seeyousoon". The three patterns differ only in the starting value and the update:

Job Start with Update
Count something let count = 0 count++ (inside an if)
Sum numbers let total = 0 total += n
Build text let text = "" text += piece

Key idea

An accumulator is a let declared before the loop with a starting value (0 to count or sum, "" to build text), updated on each pass, and used after the loop.

Watch out

Declaring the accumulator inside the loop. The three steps go in three different places, and step 1 is outside:

sum-inside.ts
for (let n = 1; n <= 4; n++) {
  let total = 0;
  total += n;
}
console.log(`Sum: ${total}`);
sum-inside.ts:5:21 - error TS2304: Cannot find name 'total'.

Two things go wrong. The let on line 2 is inside the body, so every pass makes a new total starting at 0, and the previous pass’s value is thrown away; the sum would never get past the current n. And a variable declared in the body has the body as its scope, so after the loop the name does not exist, which is what the checker reports on line 5. Move the let total = 0; above the loop. Fix or delete the file before your next check.

Pause and try

Question 12 · Debugging

This program should show the sum of 1 to 10, which is 55. npx tsc accepts it, but it shows the wrong number. Predict what it shows, explain why, and write the fix.

sum-one-to-ten.ts
let total = 0;
for (let n = 1; n < 10; n++) {
  total += n;
}
console.log(`Sum of 1 to 10: ${total}`);
Check your reasoning
Sum of 1 to 10: 45

The condition is n < 10, so the last pass has n at 9, and 10 is never added: 55 - 10 is 45. It is an off-by-one error, like the one in 5.4 but in the other direction, one pass too few. “1 to 10” includes 10, so the condition needs <=:

sum-one-to-ten-fixed.ts
let total = 0;
for (let n = 1; n <= 10; n++) {
  total += n;
}
console.log(`Sum of 1 to 10: ${total}`);
Sum of 1 to 10: 55

Neither the checker nor node can see this bug; only reading the boundary can. If you typed the original, fix it now.

Reread 5.8 Accumulators: Counting and Summing and the Watch Out in 5.4 Visiting Every Index if you missed it.

Question 13 · Tracing

Predict exactly what this program shows. Two accumulators change at different times.

count-and-sum.ts
let count = 0;
let total = 0;
for (let n = 2; n <= 10; n += 2) {
  if (n % 4 === 0) {
    count++;
  }
  total += n;
}
console.log(count, total);
Check your reasoning
2 30
n n % 4 === 0 count after total after
2 false 0 2
4 true 1 6
6 false 1 12
8 true 2 20
10 false 2 30

n goes up by 2, so the loop visits the even numbers from 2 to 10. total += n is outside the if, so it runs on every pass; count++ is inside, so it runs only for 4 and 8.

Reread 5.8 Accumulators: Counting and Summing if any value differed.

Section 9 of 10

5.9 Finding the Largest or Smallest

A week of rainfall readings, one digit per day: "3482516". Which day was the wettest? A person scans the digits and keeps the biggest one in mind, replacing it whenever a bigger one comes along. A program does the same with an accumulator that holds “the biggest so far.”

The starting value needs care. For a sum, 0 means “nothing yet.” For a maximum, there is no number that is smaller than every possible reading, so the safe start is the first value itself: after one reading, the biggest so far is that reading. Then the loop compares every value with the best so far and replaces it when it finds a bigger one.

Worked example: The wettest day

This needs the index as well as the value, to say which day won, so it uses 5.4’s counting loop.

wettest.ts
const rainfall: string = "3482516";
let most = Number(rainfall[0]);
let wettestDay = 1;
for (let i = 0; i < rainfall.length; i++) {
  const mm = Number(rainfall[i]);
  if (mm > most) {
    most = mm;
    wettestDay = i + 1;
  }
}
console.log(`Wettest: day ${wettestDay} with ${most} mm`);
Wettest: day 3 with 8 mm
i mm mm > most most, wettestDay after
0 3 3 > 3, false 3, 1
1 4 true 4, 2
2 8 true 8, 3
3 2 false 8, 3
4 5 false 8, 3
5 1 false 8, 3
6 6 false 8, 3

Line 2 starts most at the first reading, Number(rainfall[0]), which is 3; rainfall[0] is the string "3", so Day 2’s Number() is needed before any comparing. Line 5 converts the current reading the same way, into a const because it does not change within the pass. On the first pass 3 > 3 is false, which is fine: the first value is already the best so far. The third reading, 8, beats 4, and nothing after it beats 8. wettestDay is i + 1 because people count days from 1 while indexes start at 0.

Now vary the comparison. For the smallest, start the same way and replace when a value is less:

driest.ts
const rainfall: string = "3482516";
let least = Number(rainfall[0]);
for (const ch of rainfall) {
  const mm = Number(ch);
  if (mm < least) {
    least = mm;
  }
}
console.log(`Driest: ${least} mm`);
Driest: 1 mm

Only the operator changed, < instead of >. This version does not need the day number, so it walks the string with for...of from 5.5, converting each character as it goes. least drops from 3 to 2 at the fourth reading and to 1 at the sixth.

Key idea

To find a largest or smallest value, start the accumulator at the first value, then compare every value with it and replace it when the new one is bigger (or smaller). Keep a second variable for the position if you need it.

Watch out

Starting a minimum at 0. Zero feels like a safe start, and for a sum it is. For a smallest value it is a bug:

driest-zero.ts
const rainfall: string = "3482516";
let least = 0;
for (const ch of rainfall) {
  const mm = Number(ch);
  if (mm < least) {
    least = mm;
  }
}
console.log(`Driest: ${least} mm`);
Driest: 0 mm

No reading is below 0, so mm < least is never true, and least stays at 0: a day that did not exist. Nothing reports it. The same mistake with a maximum starting at 0 looks fine for rainfall but breaks as soon as every value is negative, such as winter temperatures. Start at the first value and both cases take care of themselves.

Declaring it with no value. You could try to let the loop assign the first value:

most-unassigned.ts
const rainfall: string = "3482516";
let most: number;
for (const ch of rainfall) {
  most = Number(ch);
}
console.log(`Most: ${most} mm`);
most-unassigned.ts:6:22 - error TS2454: Variable 'most' is used before being assigned.

This is Day 2’s TS2454, which Day 4 met again with an if chain that had no else. The checker does not know how many characters rainfall has, so as far as it can see, the loop might run zero times and most might still be empty on line 6. Give it a value before the loop, as wettest.ts does. Fix or delete the file before your next check.

Pause and try

Question 14 · Tracing

Predict exactly what this program shows. The comparison is >=, not >.

best-day.ts
const sales: string = "5737";
let best = Number(sales[0]);
let bestDay = 1;
for (let i = 0; i < sales.length; i++) {
  const sold = Number(sales[i]);
  if (sold >= best) {
    best = sold;
    bestDay = i + 1;
  }
}
console.log(`Best: day ${bestDay}, ${best} sold`);
Check your reasoning
Best: day 4, 7 sold
i sold sold >= best best, bestDay after
0 5 true 5, 1
1 7 true 7, 2
2 3 false 7, 2
3 7 true 7, 4

Days 2 and 4 tie at 7. With >=, a value equal to the best so far also replaces it, so the last of the tied days wins and bestDay ends at 4. With > as in wettest.ts, the first tie would have been kept, and the answer would be day 2. Choose the operator by deciding which of two equal values you want to report.

Reread 5.9 Finding the Largest or Smallest if your output differed.

Section 10 of 10

5.10 Nested Loops

A theater has rows A and B with three seats each, and you want a list: A1, A2, A3, B1, B2, B3. That is two counts at once: for each row, count the seats. A loop body can hold any statements, including another loop. A loop inside a loop is a nested loop: the outer loop runs its body once per pass, and the inner loop runs all of its passes each time.

Worked example: Every pair

pairs.ts
for (let a = 0; a < 2; a++) {
  for (let b = 0; b < 3; b++) {
    console.log(a, b);
  }
  console.log("--");
}
0 0
0 1
0 2
--
1 0
1 1
1 2
--
Outer pass a Inner loop runs with b at Then line 5
1 0 0, 1, 2 --
2 1 0, 1, 2 --

On the first outer pass, a is 0 and the whole inner loop runs: b goes 0, 1, 2, and line 3 runs three times. Then line 5 shows --, the outer update makes a 1, and the inner loop starts again from the beginning, because its header’s let b = 0 runs each time the inner loop is reached. Line 3 runs 2 × 3 = 6 times in all: the number of passes of a nested loop is the outer count times the inner count.

The two loops need not be the same kind. For the seats, walk the rows with for...of and count the seats with for:

seats.ts
for (const row of "AB") {
  for (let seat = 1; seat <= 3; seat++) {
    console.log(`${row}${seat}`);
  }
}
console.log("All seats listed");
A1
A2
A3
B1
B2
B3
All seats listed

The inner body can use both loop variables, row and seat, because it is inside both loops’ scopes. Line 6 is outside both, and runs once at the end.

Now a grid. A table of the sums of two dice, 1 to 3 each, needs one printed line per value of the first die, with one number per value of the second. The trick is a string accumulator from 5.8 that is reset in the outer loop and built in the inner loop:

dice-sums.ts
for (let first = 1; first <= 3; first++) {
  let line = "";
  for (let second = 1; second <= 3; second++) {
    line += String(first + second).padStart(3);
  }
  console.log(line);
}
  2  3  4
  3  4  5
  4  5  6
Outer pass line starts as Inner loop adds Line 6 shows
1 "" " 2", " 3", " 4" 2 3 4
2 "" " 3", " 4", " 5" 3 4 5
3 "" " 4", " 5", " 6" 4 5 6

Line 2 makes a fresh, empty line for each row. Line 4 pads each sum to three characters with Day 3’s padStart, so the columns line up, and joins it on. Line 6 is in the outer body but after the inner loop, so it runs once per row, when the row’s string is complete.

Key idea

In a nested loop, the inner loop runs all of its passes for every single pass of the outer loop, so the body runs outer × inner times. To print a grid, build each row’s text in the inner loop and print it once in the outer loop.

Watch out

Printing inside the inner loop. Move line 6 of dice-sums.ts into the inner loop (here with two rows, to keep it short):

dice-sums-wrong.ts
for (let first = 1; first <= 2; first++) {
  let line = "";
  for (let second = 1; second <= 3; second++) {
    line += String(first + second).padStart(3);
    console.log(line);
  }
}
  2
  2  3
  2  3  4
  3
  3  4
  3  4  5

console.log(line) now runs on every inner pass, showing the row as it grows: three lines per row instead of one. Nothing reports it; the output just looks wrong. When a nested loop prints too much, check which loop the console.log is inside: a statement that should happen once per row belongs in the outer body, after the inner loop’s }.

Pause and try

Question 15 · Tracing

Predict exactly what this program shows. The inner loop’s condition depends on the outer variable.

nested-total.ts
let total = 0;
for (let outer = 1; outer <= 3; outer++) {
  for (let inner = 0; inner < outer; inner++) {
    total++;
  }
  console.log(outer, total);
}
Check your reasoning
1 1
2 3
3 6
outer Inner passes (inner < outer) total after Line 6 shows
1 1 (inner at 0) 1 1 1
2 2 (0, 1) 3 2 3
3 3 (0, 1, 2) 6 3 6

The inner loop runs outer times, so total grows by 1, then 2, then 3. It is an accumulator declared outside both loops, so it keeps its value across every pass of both. The inner count can depend on the outer variable because the inner header is worked out fresh each time the inner loop starts.

Reread 5.10 Nested Loops if any line differed.

Question 16 · Multiple choice

for (let r = 1; r <= 3; r++) contains for (let c = 1; c <= 4; c++), whose body is one console.log. How many lines are shown?

  1. 7
  2. 12
  3. 3
  4. 4
Check your reasoning

B. The inner loop runs all four of its passes for each of the three outer passes: 3 × 4 = 12 lines.

  • A adds the counts instead of multiplying them. The inner loop does not run once in total; it runs once per outer pass.
  • C is the number of outer passes, which is how many rows there would be if each row were built up and printed once.
  • D is the number of inner passes per row, not in total.

Reread 5.10 Nested Loops if you chose differently.

Wrap-up · 1 of 8

Putting it together

A sentence report: how many words, how many letters, and how long the longest word is. The program walks the sentence once with for...of, using an accumulator for each count, continue to keep the “this is a letter” case at the top, and 5.9’s pattern for the longest word. Before you type it, make sure npx tsc is clean in your day05 folder: fix or delete any broken file from today.

sentence-report.ts
const sentence: string = "Loops repeat work, so you write it once.";
const alphabet = "abcdefghijklmnopqrstuvwxyz";
let words = 0;
let letters = 0;
let current = 0;
let longest = 0;
for (const ch of sentence.toLowerCase()) {
  if (alphabet.includes(ch)) {
    letters++;
    current++;
    continue;
  }
  if (current > 0) {
    words++;
    if (current > longest) {
      longest = current;
    }
    current = 0;
  }
}
if (current > 0) {
  words++;
  if (current > longest) {
    longest = current;
  }
}
console.log(`Words: ${words}`);
console.log(`Letters: ${letters}`);
console.log(`Longest word: ${longest} letters`);

npx tsc reports no errors, and node sentence-report.ts shows:

Words: 8
Letters: 31
Longest word: 6 letters

current counts the letters of the word being read right now; the other three are results. Follow the first two words:

Character Line 8: a letter? What happens Idea
l … s true ×5 letters and current each reach 5; continue 5.7, 5.8
false current is 5, so words becomes 1; longest becomes 5; current back to 0 5.9
r … t true ×6 letters reaches 11, current 6; continue 5.8
false words 2; 6 > 5, so longest is 6; current 0 5.9

The continue on line 11 means everything from line 13 on only runs for a character that is not a letter: a space, comma, or full stop. Such a character ends a word, but only if current is above 0; that guard stops the comma-then-space after work from counting two words. Lines 21 to 26 repeat the word-ending step once more after the loop, for a sentence that ends without punctuation; here the full stop already ended once, so current is 0 and the block is skipped. In all: 8 words, 31 letters, and repeat at 6 letters is the longest. Change the sentence on line 1 and only the numbers change.

Wrap-up · 2 of 8

Common mistakes

Today’s messages and silent surprises in one place. The first group comes from npx tsc; the second shows no message at all.

Message or symptom Usual cause Fix
TS2588: Cannot assign to 'lap' because it is a constant. for (const lap = 1; ...), or += on a const Declare it with let
TS2322: Type 'string' is not assignable to type 'number'. lives += "1" lives += 1 or lives++
TS2304: Cannot find name 'i'. Using the loop variable, or a variable declared in the body, after the loop Declare it before the loop
TS2407: The right-hand side of a 'for...in' statement must be ... in instead of of with a string for (const ch of text)
TS1105: A 'break' statement can only be used within an enclosing iteration ... break outside any loop or switch Use if/else; delete the break
TS2454: Variable 'most' is used before being assigned. let most: number; assigned only inside the loop Start it at the first value
The program never ends (Ctrl+C) The body never changes the condition; continue before the update in a while Update the variable so the condition can become false
undefined on the last pass, or a result one too small <= where < was meant, or the other way round Check the first and last values of the loop variable
A minimum of 0, or a maximum that ignores negatives Starting the accumulator at 0 Start at the first value
A grid prints a growing row console.log inside the inner loop Print once per row, after the inner loop
Wrap-up · 3 of 8

Vocabulary

Term Definition Example
loop A statement that runs a block repeatedly while, for, for...of
iteration / pass One run of a loop’s body countdown.ts has three
while loop Repeats its body as long as its condition is true, checking before each pass while (count > 0) { ... }
loop condition The expression that decides whether another pass runs savings < 100
loop body The block a loop repeats { console.log(count); count--; }
infinite loop A loop whose condition never becomes false; stop it with Ctrl+C while (count > 0) with no update
compound assignment operator +=, -=, *=, /=: changes a variable by an amount in place total += n
increment / decrement x++ adds 1 to x; x-- subtracts 1 lives--
for loop A loop with start, condition, and update in its header for (let i = 0; i < 5; i++)
loop variable The variable a for counts with; its scope is the loop i
off-by-one error A loop that runs one pass too many or too few i <= word.length
for…of loop Runs its body once per character of a string, with no index for (const ch of word)
break Ends the loop at once; the program carries on after the loop if (found) { break; }
flag A boolean that records whether something happened in a loop let hasDigit = false;
continue Ends the current pass and goes on to the next one if (ch === " ") { continue; }
accumulator A variable declared before a loop that collects a result across the passes let total = 0;
nested loop A loop inside another loop’s body; the inner loop runs fully for each outer pass pairs.ts
Wrap-up · 4 of 8

Summary

  • A loop repeats a block. while checks its condition before every pass and stops when it is false, so something in the body must change the condition, or you get an infinite loop (Ctrl+C stops it).
  • x += n, x -= n, x++, and x-- update a let in place, and for (start; condition; update) keeps a count’s three parts together. Use for when the number of passes is known, while when the loop runs until something happens.
  • for (let i = 0; i < text.length; i++) visits every index; for (const ch of text) visits every character without one. Check the first and last values of every loop variable for off-by-one errors.
  • break ends the loop; continue ends only the current pass. In a while, update before the continue.
  • An accumulator is declared before the loop (0 to count or sum, "" to build text, the first value for a largest or smallest), updated inside, and used after.
  • In a nested loop the inner loop runs completely for each outer pass, so a grid is built row by row: reset the row in the outer loop, build it in the inner one, print it after the inner loop.
Wrap-up · 5 of 8

Practice

Do these in your day05 folder. First make sure npx tsc prints nothing there: if any broken file from today is still in the folder (such as compound-wrong.ts, const-counter.ts, loop-scope.ts, for-in.ts, break-outside.ts, sum-inside.ts, most-unassigned.ts, or the question’s sum-one-to-ten.ts), fix it or delete it. Then type each program yourself, check it with npx tsc, run it with node, and only then open the answer. Change the starting values and run them again.

Question 17 · Short answer

FizzBuzz. Show the numbers from 1 to 30, one per line, except that for multiples of 3 show Fizz instead, for multiples of 5 show Buzz, and for multiples of both show FizzBuzz.

Check your reasoning

One possible solution:

fizz-buzz.ts
for (let n = 1; n <= 30; n++) {
  if (n % 15 === 0) {
    console.log("FizzBuzz");
  } else if (n % 3 === 0) {
    console.log("Fizz");
  } else if (n % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(n);
  }
}
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
17
Fizz
19
Buzz
Fizz
22
23
Fizz
Buzz
26
Fizz
28
29
FizzBuzz

A counting for visits 1 to 30, and an if chain from Day 4 decides what to show for each. The chain tests the multiples of both first, as n % 15 === 0 (a number divisible by 3 and by 5 is divisible by 15), because the chain runs the first true rung: with n % 3 === 0 first, 15 would show Fizz and never reach the FizzBuzz rung. n % 3 === 0 && n % 5 === 0 works just as well for the first rung. Try 1 to 100.

Reread 5.3 Counting with for if your result differed.

Question 18 · Short answer

Digit sum. Store a whole number in a constant and show the sum of its digits, using only % and Math.floor, no strings. For 4096 the answer is 4 + 0 + 9 + 6 = 19.

Check your reasoning

One possible solution:

digit-sum.ts
const number: number = 4096;
let rest = number;
let sum = 0;
while (rest > 0) {
  sum += rest % 10;
  rest = Math.floor(rest / 10);
}
console.log(`The digits of ${number} add up to ${sum}`);
The digits of 4096 add up to 19

Day 2’s % and Math.floor do the work: n % 10 is what is left after taking out all the whole tens, which is the last digit of n, and Math.floor(n / 10) counts the whole tens, which is n with that digit removed (4096 % 10 is 6, and Math.floor(4096 / 10) is 409). The loop takes the last digit off rest on every pass and adds it to the accumulator, until nothing is left. It is a while loop because the number of passes is the number of digits, which the program does not know in advance; rest reaches 0 when the last digit has gone, and the condition rest > 0 is false.

Pass rest % 10 sum after rest after
1 6 6 409
2 9 15 40
3 0 15 4
4 4 19 0

rest is a copy of number because the loop destroys it, and the message still needs the original. Try 7, 1000, and 999999.

Reread 5.1 Repeating with while and 5.8 Accumulators: Counting and Summing if your result differed.

Question 19 · Short answer

Multiplication table. Show the multiplication table for 1 to 9: nine rows, each with the products of the row number and 1 to 9, in columns that line up. Use nested loops and padStart.

Check your reasoning

One possible solution:

times-table.ts
for (let row = 1; row <= 9; row++) {
  let line = "";
  for (let column = 1; column <= 9; column++) {
    line += String(row * column).padStart(4);
  }
  console.log(line);
}
   1   2   3   4   5   6   7   8   9
   2   4   6   8  10  12  14  16  18
   3   6   9  12  15  18  21  24  27
   4   8  12  16  20  24  28  32  36
   5  10  15  20  25  30  35  40  45
   6  12  18  24  30  36  42  48  54
   7  14  21  28  35  42  49  56  63
   8  16  24  32  40  48  56  64  72
   9  18  27  36  45  54  63  72  81

The same shape as dice-sums.ts: the outer loop runs once per row, resets line to "", and prints it after the inner loop has joined on nine products. padStart(4) makes every product four characters wide, so 1 and 81 take the same space and the columns line up. Change both 9s to 12 and the widest product, 144, still fits in four characters.

Reread 5.10 Nested Loops if your result differed.

Wrap-up · 6 of 8

Review questions

Question 20 · Tracing

Predict exactly what this program shows. Track both variables on every pass.

reverse-number.ts
let rest = 1230;
let reversed = 0;
while (rest > 0) {
  reversed = reversed * 10 + (rest % 10);
  rest = Math.floor(rest / 10);
}
console.log(reversed);
Check your reasoning
321
Pass rest % 10 reversed after rest after
1 0 0 * 10 + 0 is 0 123
2 3 0 * 10 + 3 is 3 12
3 2 3 * 10 + 2 is 32 1
4 1 32 * 10 + 1 is 321 0

Each pass takes the last digit off rest and attaches it to the right end of reversed, which is multiplied by 10 first to make room. The 0 that was at the end of 1230 goes on first, and a number cannot keep a leading zero, so the result is 321, not 0321.

Reread 5.1 Repeating with while and 5.8 Accumulators: Counting and Summing if your output differed.

Question 21 · Multiple choice

A program must keep taking 7% off a price until it drops below $50, and then report how many reductions it took. Which loop fits best, and why?

  1. A counting for, because it keeps the start, condition, and update together
  2. for...of, because it visits each reduction in turn
  3. while, because nobody knows in advance how many passes it will take
  4. A nested loop, because there are two values, the price and the count
Check your reasoning

C. The loop runs “until the price is below 50,” and the number of passes depends on the starting price. That is exactly what while is for, with a separate counter as an accumulator.

  • A is wrong: a counting for is for a number of passes you know or can calculate. Here the stopping test is about the price, not a count.
  • B is wrong: for...of walks through the characters of a string. There is no string here.
  • D is wrong: two variables changing in one loop is ordinary; a nested loop is for a count inside a count, such as seats within rows.

Reread 5.3 Counting with for and 5.1 Repeating with while if you chose differently.

Question 22 · Debugging

This program should count the ls in "lollipop", which has three. npx tsc accepts it, but it shows 2. Explain why, and write the fix.

count-letters.ts
const word: string = "lollipop";
let count = 0;
for (let i = 1; i <= word.length; i++) {
  if (word[i] === "l") {
    count++;
  }
}
console.log(`${count} l's in ${word}`);
Check your reasoning

The header is let i = 1; i <= word.length, which is wrong at both ends. It starts at 1, so index 0, the first l, is never checked: that is the missing one. And it ends at word.length, which is 8, so the last pass reads word[8], which is undefined; that pass does no harm here, because undefined === "l" is false, but it is one pass too many. Indexes go from 0 to length - 1:

count-letters-fixed.ts
const word: string = "lollipop";
let count = 0;
for (let i = 0; i < word.length; i++) {
  if (word[i] === "l") {
    count++;
  }
}
console.log(`${count} l's in ${word}`);
3 l's in lollipop

The checker cannot see either slip, because the types are fine on every pass. If you typed the original, fix it now.

Reread 5.4 Visiting Every Index if you missed it.

Question 23 · Tracing

Predict exactly what this program shows. Which loop does the break leave?

nested-break.ts
for (let row = 1; row <= 3; row++) {
  for (let col = 1; col <= 3; col++) {
    if (col > row) {
      break;
    }
    console.log(row, col);
  }
}
console.log("Done");
Check your reasoning
1 1
2 1
2 2
3 1
3 2
3 3
Done

break leaves only the loop it is directly inside: the inner one. For row 1, col 1 is shown, then col 2 is above row and the inner loop ends; the outer loop carries on to row 2. Each row shows col from 1 up to row, so the rows get longer, and Done shows once at the end. Leaving the outer loop too would need a flag checked after the inner loop.

Reread 5.10 Nested Loops and 5.6 Leaving a Loop Early with break if your output differed.

Question 24 · Short answer

Sam writes let longest = 0; before a loop that finds the longest word, and let coldest = 0; before a loop that finds the lowest temperature in a week of readings. One of these starting values is fine and one is a bug. Say which is which, explain, and give a start that works for both.

Check your reasoning

Model answer: longest = 0 is fine, because a word’s length is never below 0, so the first word is longer and replaces the 0. coldest = 0 is a bug: if every reading is above 0, no reading is below coldest, it is never replaced, and the program reports a temperature of 0 that never happened. (If the readings can be below 0, the same start would be wrong for a highest temperature instead.) The start that works for both is the first value itself: after one word or one reading, that value is the best so far, and the loop only has to compare the rest.

A complete answer must:

  • explain that an accumulator for a smallest or largest value is only replaced by a better value, so the start must not beat every real value,
  • say that 0 is safe only when every real value is on the right side of it, and
  • give “start at the first value” as the fix.

Reread 5.9 Finding the Largest or Smallest if your reasoning differed.

Question 25 · Multiple choice

Which of these loops never ends?

  1. let n = 10; while (n > 0) { n -= 3; }
  2. for (let i = 0; i < 5; i--) { console.log(i); }
  3. let n = 0; while (n < 5) { n++; if (n === 2) { continue; } }
  4. for (const ch of "") { console.log(ch); }
Check your reasoning

B. The update is i--, so i goes 0, -1, -2, …, always below 5, and the condition never becomes false. The loop prints forever until Ctrl+C.

  • A ends: n goes 10, 7, 4, 1, -2, and -2 > 0 is false. A condition does not need to hit exactly 0.
  • C ends: n++ comes before the continue, so n still moves on when 2 is skipped, and reaches 5.
  • D ends at once: the empty string has no characters, so the body runs zero times.

Reread 5.1 Repeating with while and 5.7 Skipping One Pass with continue if you chose differently.

Wrap-up · 7 of 8

Go further

MDN’s guide covers every loop from today, plus a few rarer ones such as do...while, which checks its condition after each pass: MDN: Loops and iteration.

Wrap-up · 8 of 8

Reflection

Check each statement. If the answer is “not yet,” reread the linked subsection.

  • I can write a while loop and say why it stops, and I know what to do about an infinite loop. Reread
  • I can update a variable with +=, -=, ++, and --. Reread
  • I can read a for header as start, condition, and update, and say how many passes it makes. Reread
  • I can visit every index of a string without an off-by-one error. Reread
  • I can walk through the characters of a string with for...of and say when to use it instead of an index. Reread
  • I can stop a search with break and record the result in a flag. Reread
  • I can skip one pass with continue, and I update before it in a while loop. Reread
  • I can count, sum, and build a string with an accumulator declared before the loop. Reread
  • I can find the largest or smallest value, starting from the first one. Reread
  • I can print a grid with nested loops, building each row and printing it once. Reread