Javascript · Loops
break and continue
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercises
Exercise 1 — Leaving a Loop Early with break
Sometimes you want to stop a loop before its natural end: you found what you were looking for, the battle is already won... The `break` keyword exits the loop immediately. You already met it in `switch`!
for (let turn = 1; turn <= 10; turn++) { console.log("Turn " + turn); if (turn === 3) { console.log("Critical hit! Battle over."); break; } } console.log("Back to the map");
The loop was planned for 10 turns, but `break` stops it at turn 3. The remaining turns never happen, and the program continues right after the loop.
Exercise 2 — Where Does It Stop?
What will this code print?
let i = 0; while (i < 100) { i += 10; if (i > 25) { break; } } console.log(i);
Options
• ```30```
• ```25```
• ```100```
• ```20```
Hint : Follow the variable turn by turn and stop as soon as the inner condition becomes true. Note that the variable has already changed when the check happens.
Exercise 3 — Stop When Found
You search your bag slot by slot for a Rare Candy hidden in slot 4. Complete the code so the search stops as soon as the candy is found.
let candySlot = 4; for (let slot = 1; slot <= 10; slot++) { console.log("Checking slot " + slot); ____ (slot === candySlot) { console.log("Found it!"); ____; } }
Options: if break while return stop exit
Hint : You need to test each slot, then use the keyword that leaves the loop for good.
Exercise 4 — Skipping a Turn with continue
`continue` is the little sibling of `break`: instead of leaving the loop, it skips the rest of the current turn and jumps straight to the next one.
for (let i = 1; i <= 6; i++) { if (i % 2 === 0) { continue; } console.log(i); }
Here, even numbers hit `continue`, so their `console.log` is skipped. Only 1, 3 and 5 are printed, but the loop itself keeps going until the end.
continue in a while Loop
In a `while` loop, `continue` jumps back to the condition check. If your update (like `i++`) is written after the `continue`, it gets skipped and you end up with an infinite loop. Put the update before the `continue`, or use a `for` loop where the update is automatic.
Exercise 5 — What Gets Skipped?
What will this code print?
for (let i = 1; i <= 5; i++) { if (i === 3) { continue; } console.log(i); }
Options
• ```1```, ```2```, ```4```, ```5```
• ```1```, ```2```
• ```1```, ```2```, ```3```, ```4```, ```5```
• ```4```, ```5```
Hint : Ask what this keyword does to the current turn only, and what happens to the turns after it.
Exercise 6 — Skip the Fainted
Your team of 4 just survived a tough battle. Each member has a random amount of HP left: 0, 20 or 40. Only Codémon with HP strictly above 0 can attack. Complete the loop so the KO members are skipped, without stopping the loop.
for (let member = 1; member <= 4; member++) { // HP left after the battle: 0, 20 or 40 let hp = Math.floor(Math.random() * 3) * 20; ____ (hp ____ 0) { ____; } console.log("Member " + member + " attacks with " + hp + " HP"); }
Options: if <= continue break while > <
Hint : The rule says who can attack: translate it carefully into the condition that skips the others, then pick the keyword that moves on to the next turn without ending the loop.
Exercise 7 — break vs continue
Match each element with its effect.
Items to match
• break
• continue
• The loop condition after continue
• The code written after the loop
Definitions
• Leaves the loop for good
• Jumps to the next turn
• Is checked again
• Runs in both cases
Exercise 8 — The Loop That Runs Until You Say Stop
A common pattern: a loop whose condition is simply `true`, with a `break` inside to decide when to stop. It's handy when the stop condition is easier to express in the middle of the block.
let attempts = 0; while (true) { attempts++; let roll = Math.floor(Math.random() * 6) + 1; console.log("Attempt " + attempts + ": rolled a " + roll); if (roll === 6) { break; } } console.log("Got a 6 after " + attempts + " attempts!");
Run it several times: the loop lasts as long as it takes to roll a 6. Without `break`, `while (true)` would never end.
Handle with Care
`while (true)` is only safe if the `break` is guaranteed to happen eventually. Before writing one, make sure there is always a way to reach it.
Exercise 9 — Counting Until break
What will this code print?
let count = 0; while (true) { count += 3; if (count >= 10) { break; } } console.log(count);
Options
• ```12```
• ```9```
• ```10```
• It never stops
Hint : Add the step to the variable one turn at a time and stop at the first value that satisfies the inner condition.
Exercise 10 — Stop at the First Shiny
You meet wild Codémon one after another. Each one has a 20% chance to be shiny. Complete the loop so it runs until a shiny appears, then stops.
let encounters = 0; while (____) { encounters++; let isShiny = Math.random() < 0.2; if (isShiny) { console.log("Shiny found!"); ____; } } console.log("Encounters: " + encounters);
Options: true break false continue encounters isShiny
Hint : The loop has no natural end written in its header, so what must the condition be? Then think about which keyword ends it from the inside.
Exercise 11 — Gone Fishing
You go fishing for Codémon and cast your line up to 10 times. The loop and the random `luck` roll (from 1 to 10) are already written: complete the inside of the loop. 1. If `luck` is 5 or less, nothing bites: print `"Cast X: nothing bites..."` and move on to the next cast 2. If `luck` is exactly 10, print `"Cast X: a shiny Aquachu!"` and stop fishing immediately 3. Otherwise, print `"Cast X: a Codémon bites!"` 4. After the loop, print `"Fishing over."`
Starter code
for (let cast = 1; cast <= 10; cast++) { let luck = Math.floor(Math.random() * 10) + 1; // Your code here }
Back to the course