Lesson 57 min read

Loops

Make your code do the same thing over and over — without writing it over and over

Why Loops?

Imagine you're a teacher and you need to write "Good job!" on 30 students' papers. You wouldn't write it by hand 30 times — you'd use a stamp. Loops are your code's stamp. They repeat a block of code as many times as you need.

JavaScript has several types of loops, each best suited for different situations:

  • for — when you know exactly how many times to loop
  • while — when you loop until a condition becomes false
  • do...while — like while, but guarantees at least one run
  • for...of — loop through values in an array (or any iterable)
  • for...in — loop through keys/properties of an object

The Classic For Loop

// for (start; condition; step)
for (let i = 1; i <= 5; i++) {
console.log(`Lap ${i} of 5`);
}
// Counting backwards
for (let countdown = 3; countdown >= 1; countdown--) {
console.log(countdown);
}
console.log("Go! 🚀");
// Looping through an array by index
let colors = ["red", "green", "blue"];
for (let i = 0; i < colors.length; i++) {
console.log(`Color ${i}: ${colors[i]}`);
}
Output
Lap 1 of 5
Lap 2 of 5
Lap 3 of 5
Lap 4 of 5
Lap 5 of 5
3
2
1
Go! 🚀
Color 0: red
Color 1: green
Color 2: blue

While & Do...While

A while loop keeps going as long as its condition is true. It's like saying "keep stirring the soup while it's not boiling yet." Be careful — if the condition never becomes false, you get an infinite loop and your program freezes!

A do...while loop is almost the same, except it checks the condition after running the code. So the code inside always runs at least once — like a restaurant that lets you taste the food before deciding if you want more.

While & Do...While

// while — check first, then run
let fuel = 3;
while (fuel > 0) {
console.log(`Fuel: ${fuel} — Vroom!`);
fuel--;
}
console.log("Out of fuel!");
// do...while — run first, then check
let password = "secret";
let attempt;
let tries = 0;
do {
attempt = ["wrong", "nope", "secret"][tries]; // simulating input
tries++;
console.log(`Attempt ${tries}: "${attempt}"`);
} while (attempt !== "secret");
console.log("Access granted!");
Output
Fuel: 3 — Vroom!
Fuel: 2 — Vroom!
Fuel: 1 — Vroom!
Out of fuel!
Attempt 1: "wrong"
Attempt 2: "nope"
Attempt 3: "secret"
Access granted!

For...Of and For...In

for...of is the modern, clean way to loop through arrays (and strings, Maps, Sets, etc.). It gives you the values directly — no need to mess with indexes.

for...in loops through the keys (property names) of an object. Be careful: for...in on arrays gives you index strings, not numbers, which can cause subtle bugs. Stick to for...of for arrays.

For...Of and For...In + Break & Continue

// for...of — loop through VALUES
let heroes = ["Batman", "Spider-Man", "Wonder Woman"];
for (let hero of heroes) {
console.log(`Hero: ${hero}`);
}
// for...in — loop through KEYS of an object
let scores = { math: 95, english: 88, science: 92 };
for (let subject in scores) {
console.log(`${subject}: ${scores[subject]}`);
}
// break — exit the loop early
let numbers = [1, 2, 3, -1, 4, 5];
for (let num of numbers) {
if (num < 0) {
console.log("Found negative! Stopping.");
break;
}
console.log(num);
}
// continue — skip this iteration and move on
for (let i = 1; i <= 6; i++) {
if (i % 2 === 0) continue; // skip even numbers
console.log(`Odd: ${i}`);
}
Output
Hero: Batman
Hero: Spider-Man
Hero: Wonder Woman
math: 95
english: 88
science: 92
1
2
3
Found negative! Stopping.
Odd: 1
Odd: 3
Odd: 5
Note: The golden rule: use for...of for arrays and for...in for objects. Mixing them up is like using a fork to eat soup — technically possible, but you'll make a mess. And always double-check your while loop has a way to stop, or you'll freeze your browser!

Quick check

How many times does this loop run: for (let i = 0; i < 3; i++) {}
ConditionalsArrays