agyanadda@gmail.com

JS For Loop

Conditions and Loops 1 min read Updated Dec 1, 2026 Topic 15 of 38

Loops repeat code.

Classic for loop

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Three parts: start (let i = 1), condition (i <= 5), step (i++).

for...of — loop over values

for (const fruit of ['apple', 'mango']) { ... }

Best for arrays and strings.

for...in — loop over keys

for (const key in student) { ... }

Used for object properties.

break and continue

  • break exits the loop completely
  • continue skips to the next round

Examples

Example — Multiplication table HTML
<input id="n" type="number" value="7" style="width:60px">
<button onclick="table()">Show table</button>
<pre id="out"></pre>

<script>
  function table() {
    const n = Number(document.getElementById('n').value);
    let text = '';
    for (let i = 1; i <= 10; i++) {
      text += `${n} x ${i} = ${n * i}\n`;
    }
    document.getElementById('out').textContent = text;
  }
  table();
</script>
Example — for...of with continue HTML
<pre id="out"></pre>

<script>
  const marks = [45, 82, 30, 91, 67];
  let text = 'Passed marks:\n';
  for (const m of marks) {
    if (m < 33) continue; // skip failed marks
    text += m + '\n';
  }
  document.getElementById('out').textContent = text;
</script>

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which loop is best for reading every value of an array?

Exercise 2 Fill in the Blank

The ___ statement skips the rest of the current loop round.

Exercise 3 True / False

for (let i = 0; i < 3; i++) runs 3 times.

Frequently Asked Questions

A loop whose condition never becomes false, such as forgetting i++. It freezes the page. Always check that the loop will end.