JavaScript: JavaScript Loops

🗓 Last updated: 2026-11-30👤 Written by: Blake✓ Reviewed by: MOTO🏷 Category: JavaScript Tutorial

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.

Related Statements:for...of forEach return while let var for

1. for Loop

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

HTML
<!-- Document type declaration -->
<!DOCTYPE html>
<!-- HTML root element -->
<html lang="en">
<!-- Document head -->
<head><meta charset="UTF-8"><title>for Loop</title></head>
<!-- Document body -->
<body>
<!-- Container element -->
<div id="output"></div>
<!-- Script tag -->
<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
💡 Tip: 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

▶ Try it Yourself

2. while Loop

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

HTML
<!-- Script tag -->
<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.


3. do...while Loop

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

HTML
<!-- Script tag -->
<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

▶ Try it Yourself

4. for...of Loop

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

HTML
<!-- Document type declaration -->
<!DOCTYPE html>
<!-- HTML root element -->
<html lang="en">
<!-- Document head -->
<head><meta charset="UTF-8"><title>for...of</title></head>
<!-- Document body -->
<body>
<!-- Container element -->
<div id="output"></div>
<!-- Script tag -->
<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.

💡 Tip: 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.


5. break and continue

HTML
<!-- Document type declaration -->
<!DOCTYPE html>
<!-- HTML root element -->
<html lang="en">
<!-- Document head -->
<head><meta charset="UTF-8"><title>break and continue</title></head>
<!-- Document body -->
<body>
<!-- Container element -->
<div id="output"></div>
<!-- Script tag -->
<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

▶ Try it Yourself

6. Nested Loops

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

HTML
<!-- Document type declaration -->
<!DOCTYPE html>
<!-- HTML root element -->
<html lang="en">
<!-- Document head -->
<head><meta charset="UTF-8"><title>Nested Loops</title></head>
<!-- Document body -->
<body>
<!-- Container element -->
<div id="output"></div>
<!-- Script tag -->
<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

▶ Try it Yourself

7. The Infinite Loop Trap

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

HTML
<!-- Script tag -->
<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>
⚠️ Note: 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.


Related Statements:for...of forEach return while let var for

❓ FAQ

Q What exactly is the difference between a for loop and a while loop in JavaScript, and when should I use each?
A for is best when the number of iterations is known or when you need the three steps of initialization, condition, and update, keeping the control logic on one line; while is best when the count is uncertain and depends only on a condition. If the loop body must run once before checking, do...while is more natural.
Q What are the most common mistakes when writing JavaScript loops?
A Common mistakes include a wrong condition causing an infinite loop (such as forgetting i++ in while(i < 10)), for...in over an array giving string indices, and declaring the loop variable with var so closures capture the same value. Declaring the loop variable with let and checking the update expression avoids most of these problems.
Q For iterating over arrays in JavaScript, is for, forEach, or for...of better?
A Use a traditional for or for...of when you need break, continue, or an early return, because forEach cannot be interrupted. For simple iteration without needing the index, for...of is the most readable; if you need the index, use for or forEach((item, i) => ...).

📖 Summary

📝 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)
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

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

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