Codiqo

Learn JavaScript · lesson 17 of 60 · about 8 minutes

while and for Loops

Give every visitor a star for each day of their streak: repeat code a set number of times with for, or until something changes with while.

What you'll learn

  • Write a counting for loop
  • Write a while loop
  • Avoid infinite loops

A star for every day

Sam wants the page to show a star for each day the visitor has been coding: five days, five stars. You could write stars += "★" five times, but the next visitor has coded for 12 days, and the one after that for 0. The number changes with every visitor, so the page needs to repeat a line as many times as it's told.

for: counting loops

A for loop puts the three parts of counting in one line:

for (start; condition; step)

1. start runs once: let i = 0
2. condition is checked before each lap: i < 3
3. step runs after each lap: i++

A counting for loop

for (let i = 0; i < 3; i++) {
  console.log("Lap", i);
}

Output

Lap 0
Lap 1
Lap 2

Step through it to watch the stars build up

let stars = "";
for (let i = 0; i < 3; i++) {
  stars += "★";
}
console.log(stars);

Output

★★★

As many stars as the visitor has days

const theirDays = 5;
let stars = "";
for (let i = 0; i < theirDays; i++) {
  stars += "★";
}
document.querySelector("#streak").textContent = `Your streak: ${stars}`;

while: repeat until it's false

A while loop checks its condition, runs its body, then checks again. Something inside the loop must eventually make the condition false, or it runs forever.

while

let fuel = 3;
while (fuel > 0) {
  console.log(`Fuel: ${fuel}`);
  fuel--;
}
console.log("Empty");

Output

Fuel: 3
Fuel: 2
Fuel: 1
Empty

Which loop?

Use for when you know how many laps there are, like one per day. Use while when you only know when to stop: Sam codes 7 days a week, so how many weeks until the 30-day badge? Nobody knows the number of laps in advance, only that the loop stops once the days reach 30.

Weeks until the 30-day badge

let days = 3;
let weeks = 0;
while (days < 30) {
  days += 7;
  weeks++;
}
console.log(`${weeks} weeks to go`);

Output

4 weeks to go

Tip

Make the counter with let. A loop changes it every lap, and a const can't change.

Now try it yourself

This lesson is free in Codiqo, with 11 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.