Loops: repeat without repeating yourself

What a loop is; count and list with for.

1. What is this?

A loop is an instruction that repeats a block of code while a condition holds. A for loop has three parts: a counter start (let i = 0), a keep-going test (i < 5), and a step (i++ means add one). The block in { } runs once per value of i.

2. Why do we use it?

Rendering 100 rows, sending reminders, processing files — all loops. Writing the block once beats copying it 100 times.

3. Syntax breakdown

  • for (let i = 0; i < 5; i++) {

    Start i at 0. Keep going while i < 5. After each pass, add 1 to i.

  •   console.log("Step " + i);

    Runs 5 times with i = 0,1,2,3,4.

  • }

    Closes the repeated block.

5. Common mistakes

  • Off-by-one: i < 5 runs 5 times from 0; i <= 5 runs 6 times. Check your start and test.
  • Forgetting i++ creates an endless loop — the counter never moves.
  • Using the counter outside the loop expecting it to keep its last meaning.

Practice task

Log the 3-times table from 3 x 1 to 3 x 5, one per line (e.g. "3 x 1 = 3").

Hint

Inside the loop use (3 * i) and build the string with +.

Try it below — tests run automatically when you press Run.

javascript

Output

Press Run to see output.

Mini quiz

3 questions. Answer, then check.

  1. 1. How many times does for (let i = 0; i < 5; i++) run?

  2. 2. What does i++ do?

  3. 3. Where does the repeated code go?

4. Example — edit and run

javascript

Output

Press Run to see output.

Expected output: Step 1