HTML chapters

Chapter 8 of 17

Loops

Try this in our HTML Compiler →

Repeating work

Loops let you run the same block of code many times — once per item in a list, once per character in a string, or until a condition becomes false. They are how you process collections of data without writing the same line a hundred times.

<!-- HTML has no loops. Repeating content is usually generated by a server or a JavaScript framework: -->
<ul>
  <li>Apple</li>
  <li>Banana</li>
  <li>Cherry</li>
</ul>

for vs while

Use a for loop when you know up-front how many times to iterate or you are walking through a collection. Use while when you have to keep going until some condition is met — for example, reading lines from a file until the end is reached.

break and continue

break stops a loop immediately and continue skips to the next iteration. Use them to handle early exit conditions, but avoid burying them deep inside a complex loop — that makes flow hard to follow.

Try it yourself

HTML Compiler
CSS (optional)
Output
Code runs in a sandboxed preview inside your browser — your code is saved locally for next time.