Back to subject
JavaScript/Loops: for, while

Repeat an Action Five Times

Practical lesson

Let's trace this for loop iteration by iteration, the way JavaScript actually runs it.

let i = 1; runs exactly once, before anything else i now holds 1. i <= 5 is checked: true, so the loop body runs, appending "Count: 1" to output. Then i++ runs, making i become 2.

The condition is checked again: i <= 5 is still true (2 <= 5), so the body runs again, appending "Count: 2". This cycle check condition, run body, increment repeats for i = 3, 4, and 5.

When i becomes 6, the condition i <= 5 finally evaluates to false, and the loop stops immediately, without running its body a sixth time this is exactly why the loop produces five lines of output (1 through 5), not six.

output += `<p>Count: ${i}</p>`; deserves attention too: += appends to the existing string rather than replacing it, which is exactly how output accumulates all five lines before being displayed at once, after the loop finishes.

Try it yourself
Code

Starter example

Code
<script>
  let output = "";
  for (let i = 1; i <= 5; i++) {
    output += `<p>Count: ${i}</p>`;
  }
  document.body.innerHTML = output;
</script>
Live preview