Lesson 7 · 7 of 20
for and while loops · JavaScript
Repeat code in JavaScript with for and while: times tables, growing savings, break, continue and a countdown.

A `for` loop has three parts in brackets: the start (let i = 1), the condition to keep going (i <= 5) and the step for each round (i++, which adds 1). That is how you print the 7 times table without writing the same line five times.
`while` repeats as long as its condition is true, without knowing in advance how many rounds it will take. The savings grow 5% a year (savings * 1.05) and the loop counts the years until they pass 130 euros: it takes 6. Make sure the condition becomes false at some point, or the loop never ends.
Inside a loop, `continue` jumps to the next round and `break` leaves the loop completely. In the game the even levels are skipped (level % 2 === 0) and play stops after level 7, even though the for went up to 10.
A loop can also build something bit by bit: countdown += n + " " adds each number to the end of the string, counting down with n--.
Code · main.js
// for: start; condition; step. A multiplication table.for (let i = 1; i <= 5; i++) { console.log(`7 x ${i} = ${7 * i}`);}// while repeats as long as the condition is true.// 100 euros saved, +5% every year: how long until 130?let savings = 100;let years = 0;while (savings < 130) { savings = savings * 1.05; years++;}console.log(`After ${years} years: ${savings.toFixed(2)} euros`);// continue jumps to the next round; break leaves the loop.for (let level = 1; level <= 10; level++) { if (level % 2 === 0) continue; // skip even levels if (level > 7) break; // stop after level 7 console.log("Playing level", level);}// A loop that builds a string step by steplet countdown = "";for (let n = 5; n >= 1; n--) { countdown += n + " ";}console.log(countdown + "Lift-off!");Output · node main.js
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35 After 6 years: 134.01 euros Playing level 1 Playing level 3 Playing level 5 Playing level 7 5 4 3 2 1 Lift-off!
Key points
for (start; condition; step)when you know how many rounds.while (condition)for as long as it holds; make sure it ends.continuejumps to the next round;breakleaves the loop.i++adds 1,n--subtracts 1 and+=appends.
Exercise
Print the 9 times table from 1 to 10, and use a while to work out how many years 200 euros take to double at 4% a year.