~/hackweb.dev
JavaScript Loops
Quiz
...

JavaScript Loops

beginner · updated Tue Sep 08 2026Contribute

Master for, while, and do...while loops for repetition.

JavaScript Loops

Loops repeat code multiple times, saving you from writing the same thing over and over.

for Loop

The most common loop. Has three parts: initialization, condition, and update:

for (let i = 0; i < 5; i++) {
  console.log(i);
}
// Output: 0, 1, 2, 3, 4
  1. Initialization (let i = 0) — runs once at start
  2. Condition (i < 5) — checked before each iteration
  3. Update (i++) — runs after each iteration

while Loop

Use when you don’t know how many times to iterate:

let i = 0;
while (i < 5) {
  console.log(i);
  i++;
}

The condition is checked before each iteration.

do...while Loop

Always runs at least once, even if condition is false:

let i = 0;
do {
  console.log(i);
  i++;
} while (i < 5);

Tip: Good for menus that must display at least once.

break and continue

// break — exit loop immediately
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i);  // 0, 1, 2, 3, 4
}

// continue — skip to next iteration
for (let i = 0; i < 10; i++) {
  if (i % 2 !== 0) continue;
  console.log(i);  // 0, 2, 4, 6, 8
}

Nested Loops

for (let i = 1; i <= 5; i++) {
  let row = "";
  for (let j = 1; j <= 5; j++) {
    row += `${i * j}\t`;
  }
  console.log(row);
}

The inner loop completes all iterations for each outer loop iteration.

Complete Example: FizzBuzz

for (let i = 1; i <= 100; i++) {
  if (i % 3 === 0 && i % 5 === 0) {
    console.log("FizzBuzz");
  } else if (i % 3 === 0) {
    console.log("Fizz");
  } else if (i % 5 === 0) {
    console.log("Buzz");
  } else {
    console.log(i);
  }
}

Complete Example: Find Value

let numbers = [3, 7, 1, 9, 4, 2, 8];
let target = 9;
let found = false;

for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] === target) {
    console.log(`Found ${target} at index ${i}`);
    found = true;
    break;
  }
}

Best Practices

  1. Use for when count is known — More readable
  2. Use while when condition-driven — More flexible
  3. Avoid infinite loops — Always have an exit condition
  4. Use break wisely — Exit early when done
  5. Use continue wisely — Skip without nesting

Common Mistakes

  1. Infinite loops — Missing increment or wrong condition
  2. Off-by-one errors — Loop runs one too many/few times
  3. Using = instead of === — Assignment in condition
  4. Forgetting braces — Only first line runs in loop
  5. Modifying array while iterating — Can skip elements