Beginner20 min read

Loops

Learn to repeat actions with for, while, do...while loops, and control loop flow with break and continue.

The for Loop

The for loop repeats a block of code a specific number of times. Its syntax has three parts:

javascript
for (initialization; condition; update) {
  // code to repeat
}
  • Initialization — Runs once before the loop starts. Typically declares a counter variable.
  • Condition — Checked before each iteration. If false, the loop stops.
  • Update — Runs after each iteration. Typically increments the counter.

The most common pattern:

javascript
for (let i = 0; i < 5; i++) {
  console.log('Iteration:', i);
}
// Output: 0, 1, 2, 3, 4

You can use for loops to iterate over arrays by index:

javascript
const colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
  console.log(colors[i]);
}

while and do...while

The while loop repeats a block of code as long as a condition is true. It checks the condition before each iteration:

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

Use a while loop when you don't know in advance how many times the loop should run — for example, reading user input until a valid value is entered.

The do...while loop is similar, but it checks the condition after each iteration. This guarantees the code block runs at least once:

javascript
let num = 10;
do {
  console.log(num);
  num++;
} while (num < 5);
// Output: 10 (runs once even though 10 < 5 is false)

Warning: Be careful to always include logic that eventually makes the condition false. Otherwise, you create an infinite loop that will freeze the browser.

break and continue

Two keywords give you finer control over loop execution:

  • break — Immediately exits the loop entirely.

    javascript
    for (let i = 0; i < 100; i++) {
      if (i === 5) break;
      console.log(i);
    }
    // Output: 0, 1, 2, 3, 4
  • continue — Skips the rest of the current iteration and moves to the next one.

    javascript
    for (let i = 0; i < 6; i++) {
      if (i === 3) continue;
      console.log(i);
    }
    // Output: 0, 1, 2, 4, 5 (3 is skipped)

For nested loops, you can use labeled statements to break or continue a specific outer loop:

javascript
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) break outer;
    console.log(i, j);
  }
}

Building a List Dynamically

html
<ul id="list"></ul>

<script>
  const fruits = ['Apple', 'Banana', 'Cherry', 'Date', 'Elderberry'];
  const list = document.getElementById('list');

  for (let i = 0; i < fruits.length; i++) {
    const li = document.createElement('li');
    li.textContent = `${i + 1}. ${fruits[i]}`;
    list.appendChild(li);
  }
</script>

How many times does `for (let i = 0; i < 3; i++)` execute its body?

Ready to practice?

Create your free account to access the interactive code editor, run challenges, and track your progress.