Data & LogicBeginner7 min07 / 12

Loops

Learn how to repeat work automatically with JavaScript's for, while, for...of, and for...in loops — and when to reach for each one.

Imagine you need to send a "Happy Birthday" message to every person in a list of 500 friends. Writing that message 500 times by hand would be absurd — and if the list grows to 501, you'd have to write it again. Loops are JavaScript's answer to this: write a task once, and tell the computer to repeat it as many times as needed. Almost every real program uses loops, whether it's rendering a list of tweets, calculating a shopping cart total, or validating each item in an order.

#The Classic for Loop

Three parts in one line: initialise (let i = 0), check (i < 5), update (i++). Use for when you know the exact count.
for (let i = 0; i < 5; i++) {
  console.log(`Step ${i}`);
}
Think of it like

A for loop is like a treadmill timer

You set the start time (initialise), the end time (condition), and the interval (update). The treadmill runs each interval until the time is up — then it stops. The for loop works the same way: initialise once, check before each step, run the body, then update.

#The while Loop

Use while when you don't know in advance how many times to repeat — just keep going while a condition holds.
let attempts = 0;
let correct = false;

while (!correct) {
  attempts++;
  if (attempts === 3) correct = true;
}

console.log(`Took ${attempts} attempt(s).`);
Common mistake

Infinite loops will freeze your program

If the condition in a while loop never becomes false, the loop runs forever and the page (or Node process) hangs. Always make sure something inside the loop eventually makes the condition false — a counter that increments, a flag that flips, or user input that changes.

#for...of and for...in

for...of gives you values from arrays; for...in gives you keys from objects. Keep them on the right job.
// for...of — each VALUE from an array
const groceries = ["eggs", "milk", "bread"];
for (const item of groceries) {
  console.log(`Buy: ${item}`);
}

// for...in — each KEY from an object
const scores = { Alice: 92, Bob: 78 };
for (const name in scores) {
  console.log(`${name}: ${scores[name]}`);
}

#forEach — Looping with a Callback

forEach is an array method that runs a function per element, passing (value, index, array). Unlike for...of, you cannot use break inside it.
const colors = ["red", "green", "blue"];

colors.forEach((color, index) => {
  console.log(`${index}: ${color}`);
});

#break and continue — Controlling the Flow

break exits the loop immediately; continue skips the rest of the current iteration and moves to the next. Both work in for, while, and for...of.
const numbers = [3, 7, 2, 9, 4, 6, 1];

for (const n of numbers) {
  if (n === 9) break;       // stop the whole loop
  if (n % 2 === 0) continue; // skip even numbers
  console.log(n);
}
Quick check

Which loop is best for visiting every item in the array `["cat", "dog", "fish"]`?

Key takeaways

  • Use `for` when you know the exact number of iterations or need a counter variable.
  • `while` loops keep running until a condition becomes false — always ensure something inside will eventually stop it.
  • `for...of` is the cleanest way to iterate over array values; `for...in` iterates over object keys.
  • `forEach` is an array method that runs a callback per element and conveniently exposes the index alongside the value.
  • `break` exits a loop immediately; `continue` skips the rest of the current iteration and moves on to the next.
Practice challenges
Test yourself · earn XP
0/4
Predict the output#1

What does this loop print to the console?

predict-output
const numbers = [3, 7, 2, 9, 4, 6, 1];

for (const n of numbers) {
  if (n === 9) break;
  if (n % 2 === 0) continue;
  console.log(n);
}
Fix the bug#2

This code has a bug — what's wrong?

fix-bug
let attempts = 0;
let correct = false;

while (!correct) {
  if (attempts === 3) correct = true;
}

console.log(`Took ${attempts} attempt(s).`);
Fill in the blank#3

Complete this classic for loop so it logs Step 0 through Step 4 (five steps total), matching the lesson's example.

for (let i = 0; i  5; i++) {
  console.log(`Step ${i}`);
}
Reorder the lines#4

Arrange these lines into a working for...of loop that buys each grocery item, exactly as taught in the lesson.

1
  console.log(`Buy: ${item}`);
2
for (const item of groceries) {
3
const groceries = ["eggs", "milk", "bread"];
4
}
Your turn
Practice exercise

You have an array of student grades. Write code that: (1) uses a for...of loop to print every grade, (2) uses continue to skip and only print passing grades (70 or above), and (3) uses a classic for loop to print each grade alongside its 1-based position number, like "1: 85".

Try it live — edit the code and hit Run to see the output:

solution.js · editable