404 Not Found

404 Not Found


nginx

JavaScript Loops

Loops let your program repeat a block of code. Writing "Hello" 100 times by hand is silly — with a loop, you write it once. That's the power of loops.

for Loop

The for loop is the most common choice when you know how many times to iterate:

HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>for Loop</title></head>
<body>
<div id="output"></div>
<script>
for (let i = 0; i < 5; i++) {
  document.getElementById('output').textContent += i + ' ';
}
</script>
</body>
</html>

The three parts:

  1. let i = 0 — initialization, runs once
  2. i < 5 — condition, checked before each iteration; continues only if true
  3. i++ — update, runs after each iteration
💡 Loop variables are conventionally named i. For nested loops, use i for the outer, j for the inner, and k for the next level — a universal programmer's convention.

Example: Generating a List with Loops

HTML
<!DOCTYPE html>
<html>
<body>
  <h2>Generate a List with Loops</h2>
  <ul id="list"></ul>
  <script>
    let fruits = ['Apple', 'Banana', 'Orange', 'Grape', 'Watermelon'];
    let html = '';
    for (let i = 0; i < fruits.length; i++) {
      html += `<li>#${i + 1}: ${fruits[i]}</li>`;
    }
    document.getElementById('list').innerHTML = html;
  </script>
</body>
</html>
▶ Try it Yourself

while Loop

while checks the condition first, then executes — ideal when you don't know how many iterations you'll need:

HTML
<script>
let count = 0;
while (count < 3) {
  count++;
}
</script>

Common use cases: reading data until it runs out, waiting for a condition to become true.

do...while Loop

do...while executes once before checking the condition — it runs at least once:

HTML
<script>
let input;
do {
  input = prompt('Enter a positive number:');
} while (Number(input) <= 0);
</script>

The difference from while in one sentence: while might never execute, but do...while always runs at least once.

Example: Comparing All Three Loops

HTML
<!DOCTYPE html>
<html>
<body>
  <h2>Comparing Three Loop Types</h2>
  <div id="output"></div>
  <script>
    let html = '<strong>for loop outputs 1-5:</strong><br>';
    for (let i = 1; i <= 5; i++) {
      html += i + ' ';
    }

    html += '<br><br><strong>while loop countdown:</strong><br>';
    let count = 5;
    while (count > 0) {
      html += count + '... ';
      count--;
    }
    html += 'Liftoff!';

    html += '<br><br><strong>do...while runs at least once:</strong><br>';
    let x = 100;
    do {
      html += 'Executed! x = ' + x + '<br>';
      x++;
    } while (x < 100);
    // Condition is false from the start, but do block runs once anyway

    document.getElementById('output').innerHTML = html;
  </script>
</body>
</html>
▶ Try it Yourself

for...of Loop

for...of is designed for iterating over iterable objects (arrays, strings, etc.) with the cleanest syntax:

HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>for...of</title></head>
<body>
<div id="output"></div>
<script>
let colors = ['Red', 'Green', 'Blue'];
let html = '';
for (let color of colors) {
  html += color + ' ';
}
document.getElementById('output').textContent = html;
</script>
</body>
</html>

Unlike for, for...of gives you the value, not the index. If you need the index, use a traditional for loop.

💡 When iterating strings with for...of, you get one character at a time — even emoji characters stay intact, which is much more reliable than index-based access.

break and continue

HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>break and continue</title></head>
<body>
<div id="output"></div>
<script>
// break: stop when target is found
let breakResult = '';
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  breakResult += i + ' ';
}

// continue: skip even numbers
let continueResult = '';
for (let i = 0; i < 6; i++) {
  if (i % 2 === 0) continue;
  continueResult += i + ' ';
}

document.getElementById('output').innerHTML =
  '<strong>break result:</strong>' + breakResult + '<br>' +
  '<strong>continue result:</strong>' + continueResult;
</script>
</body>
</html>

Example: break and continue in Action

HTML
<!DOCTYPE html>
<html>
<body>
  <h2>break and continue</h2>
  <div id="output"></div>
  <script>
    let html = '<strong>break — stop at the first even number:</strong><br>';
    let nums = [1, 3, 7, 4, 9, 2];
    for (let n of nums) {
      if (n % 2 === 0) {
        html += `Found even number ${n}, stopping!`;
        break;
      }
      html += `${n} is odd, continuing...<br>`;
    }

    html += '<br><br><strong>continue — output odd numbers only:</strong><br>';
    for (let i = 1; i <= 10; i++) {
      if (i % 2 === 0) continue;
      html += i + ' ';
    }

    html += '<br><br><strong>Practical example — searching:</strong><br>';
    let students = [
      { name: 'Alice', score: 95 },
      { name: 'Bob', score: 72 },
      { name: 'Charlie', score: 88 }
    ];
    let found = false;
    for (let s of students) {
      if (s.score >= 90) {
        html += `Found top student: ${s.name} (${s.score} pts)`;
        found = true;
        break;
      }
    }
    if (!found) {
      html += 'No student scored 90 or above';
    }

    document.getElementById('output').innerHTML = html;
  </script>
</body>
</html>
▶ Try it Yourself

Nested Loops

Loops can be nested inside other loops — most commonly used for working with 2D data (tables, grids):

HTML
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Nested Loops</title></head>
<body>
<div id="output"></div>
<script>
let html = '';
for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    html += `(${i}, ${j}) `;
  }
  html += '<br>';
}
document.getElementById('output').innerHTML = html;
</script>
</body>
</html>

Nested loops multiply in cost — 10 outer × 10 inner = 100 iterations. Too many levels can severely slow things down; if there's an alternative, avoid deep nesting.

Example: Multiplication Table

HTML
<!DOCTYPE html>
<html>
<body>
  <h2>Multiplication Table</h2>
  <table id="table" border="1" cellpadding="6" style="border-collapse:collapse"></table>
  <script>
    let html = '';
    for (let i = 1; i <= 9; i++) {
      html += '<tr>';
      for (let j = 1; j <= i; j++) {
        html += `<td style="text-align:center">${j}×${i}=${i * j}</td>`;
      }
      html += '</tr>';
    }
    document.getElementById('table').innerHTML = html;
  </script>
</body>
</html>
▶ Try it Yourself

The Infinite Loop Trap

If a loop's condition is always true, your program will freeze — this is an infinite loop:

HTML
<script>
// ⚠️ Never do this!
// while (true) {
//   console.log('I can never stop!');
// }

// Common mistake: forgetting to update the condition
let i = 0;
// while (i < 5) {
//   console.log(i);
//   Forgot i++, so i is always 0 and the loop never ends
// }
</script>
⚠️ When writing loops, always verify that the condition will eventually become false. Otherwise the browser will freeze and you'll have to force-close the tab.


📖 Summary

  1. for is most common for known iteration counts; while for condition-driven; do...while runs at least once
  2. for...of is the cleanest way to iterate arrays — gives values, not indices
  3. break exits the entire loop; continue skips to the next iteration
  4. Nested loops multiply in iteration count — avoid going too deep
  5. Always ensure loop conditions will eventually become false to avoid infinite loops

❓ FAQ

Q What's the difference between for...of and for...in?
A for...of iterates values and works with arrays and iterables; for...in iterates keys (indices) and is meant for objects. Use for...of for arrays — for...in can pick up prototype chain properties and cause unexpected issues.
Q Which loop has the best performance?
A Traditional for loops are fastest; for...of is slightly slower but more readable. In most cases the performance difference is negligible — prioritize readability.
Q Does break in a nested loop exit all loops or just the inner one?
A Only the innermost loop. To break out of an outer loop, use a label: outer: for(...) { for(...) { break outer; } }. But labels hurt readability — consider refactoring into a function and using return instead.

📝 Exercises

  1. Use a for loop to print all multiples of 3 between 1 and 100
  2. Use nested loops to render an 8×8 checkerboard pattern (alternating black and white squares) on the page
  3. Write a program that takes a positive integer as input and outputs its factorial (e.g., input 5 → 5×4×3×2×1 = 120)
100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏