Javascript · Loops
The for Loop
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — Repeating Without Copy-Pasting
Imagine Pyrochu has to train 5 times. You could write the same `console.log` five times... but what about 100 times? Or 1000?
console.log("Pyrochu trains!"); console.log("Pyrochu trains!"); console.log("Pyrochu trains!"); console.log("Pyrochu trains!"); console.log("Pyrochu trains!");
A loop repeats a block of code for you. Here is the exact same result with a `for` loop:
for (let i = 0; i < 5; i++) { console.log("Pyrochu trains!"); }
One block, five executions. Try changing `5` to `100` and run again: no copy-pasting needed!
Exercise 2 — Anatomy of a for Loop
A `for` loop header has three parts, separated by semicolons:
for (initialization; condition; update) { // code repeated at each turn }
1. Initialization: creates the counter, runs once at the start → `let i = 0` 2. Condition: checked before each turn, the loop continues while it is `true` → `i < 3` 3. Update: runs after each turn → `i++` (adds 1 to `i`)
for (let i = 0; i < 3; i++) { console.log("Turn number " + i); } console.log("Training over");
The counter `i` is available inside the block. It goes 0, 1, 2, then the condition `3 < 3` is `false` and the loop stops. Each pass through the block is called an iteration.
Exercise 3 — How Many Times?
How many times is `Aquachu attacks!` printed?
for (let i = 1; i < 3; i++) { console.log("Aquachu attacks!"); }
Options
• ```2```
• ```3```
• ```4```
• Infinitely
Hint : Walk through the values of the counter one by one and check the condition each time. Pay attention to whether the limit itself passes the test.
Exercise 4 — Complete the Loop Header
Complete the loop so it prints the message exactly 4 times.
for (____ i = 0; i ____ 4; i____) { console.log("Florachu grows!"); }
Options: let < ++ const <= --
Hint : The counter changes at every turn, so pick a keyword that allows that. Then make the condition and the update work together to get exactly four turns, starting from 0.
Exercise 5 — Using the Counter
The counter isn't just for counting turns: you can use its value inside the block. Here, every turn deals more damage than the previous one:
for (let turn = 1; turn <= 4; turn++) { let damage = turn * 10; console.log("Turn " + turn + ": " + damage + " damage"); }
The counter can have any name, not just `i`. It can also start anywhere, or count backwards:
// Countdown before the battle for (let count = 3; count > 0; count--) { console.log(count + "..."); } console.log("Fight!");
And the update doesn't have to be `++`: any change works, like jumping 2 by 2.
// Only even levels, with a step of 2 for (let level = 2; level <= 10; level += 2) { console.log("Level " + level + " reached"); }
Exercise 6 — Which Values Are Printed?
What will this code print?
for (let i = 1; i <= 10; i += 3) { console.log(i); }
Options
• ```1```, ```4```, ```7```, ```10```
• ```1```, ```4```, ```7```
• Every number from ```1``` to ```10```
• ```3```, ```6```, ```9```
Hint : Start from the initial value and apply the update each time. Stop only when the condition becomes false, and check whether the last value still passes it.
Exercise 7 — Countdown
Complete this loop so it counts down from 5 to 1 before Zap's attack.
for (let i = 5; i ____ 1; i____) { console.log(i); } console.log("Thunder!");
Options: >= -- ++ > <=
Hint : The counter has to go down at every turn, and the loop must still run when the counter reaches the last number you want to display.
Exercise 8 — Parts of a for Loop
Match each part of a `for` loop with its role.
Items to match
• let i = 0
• i < 5
• i++
• { }
Definitions
• Initialization: creates the counter
• Condition: checked before each turn
• Update: runs after each turn
• Block: the code to repeat
Exercise 9 — Accumulating with a Loop
A very common pattern: a variable created before the loop and updated at each turn. That's how you compute a total.
let totalXP = 0; for (let battle = 1; battle <= 4; battle++) { totalXP += 25; console.log("After battle " + battle + ": " + totalXP + " XP"); } console.log("Total: " + totalXP + " XP");
`totalXP` must be declared outside the loop. If you created it inside the block, it would be reset to 0 at every turn!
The counter itself can be added to the total. Here is the sum of the levels 1 to 5:
let sum = 0; for (let level = 1; level <= 5; level++) { sum += level; } console.log(sum);
Loops and Strings
Remember indexing? `name[i]` gives one character, and `name.length` gives the number of characters. Combined with a loop, you can visit every letter of a string:
for (let i = 0; i < name.length; i++)
Exercise 10 — Final Value
What will this code print?
let coins = 10; for (let i = 0; i < 3; i++) { coins *= 2; } console.log(coins);
Options
• ```80```
• ```60```
• ```20```
• ```16```
Hint : Follow the value of the variable turn by turn, starting from its initial value. Count how many turns the loop actually makes.
Exercise 11 — Total Damage
Pyrochu attacks 3 times, and each hit deals 15 damage. Complete the loop to compute the total damage.
let totalDamage = ____; for (let hit = 1; hit ____ 3; hit++) { totalDamage ____ 15; } console.log(totalDamage);
Options: 0 <= += 15 < = -=
Hint : Think about what the total should be before any hit has landed, how many turns the loop needs, and how each hit should change the total.
Exercise 12 — Training Program
Rockachu starts a 5-day training program. 1. For each day from 1 to 5, print `"Day X: training"` where X is the day number 2. Each day, Rockachu gains 12 XP: keep track of the total in `totalXP` 3. After the loop, print the total XP
Starter code
let totalXP = 0; // Write your loop here
Back to the course