JavaScript Loops

Repeating Code

Loops allow you to execute code multiple times. They're essential for processing arrays and repeating tasks.

JavaScript has several types of loops: for, while, do-while, and for-of.

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

// Looping Through Array
const fruits = ['apple', 'banana', 'orange'];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// While Loop
let count = 0;
while (count < 5) {
  console.log('Count: ' + count);
  count++;
}

// Do-While Loop (executes at least once)
let num = 0;
do {
  console.log('Number: ' + num);
  num++;
} while (num < 5);

// For-Of Loop (modern way)
for (let fruit of fruits) {
  console.log(fruit);
}

// Break and Continue
for (let i = 0; i < 10; i++) {
  if (i === 5) break;      // Stop loop
  if (i === 2) continue;   // Skip iteration
  console.log(i);
}
// Output: 0, 1, 3, 4
  • for - Loop with counter
  • while - Loop while condition is true
  • do-while - Loop at least once
  • for-of - Loop through array values
  • break - Exit loop early
  • continue - Skip current iteration
  • Avoid infinite loops!

Try Loops

<div class="loop-demo">
  <h3>Multiplication Table</h3>
  <input type="number" id="tableNum" value="5" min="1" max="20">
  <button onclick="showTable()">Generate Table</button>
  <div id="tableOutput"></div>
  
  <hr style="margin: 20px 0;">
  
  <h3>Number Patterns</h3>
  <button onclick="showPatterns()">Show Patterns</button>
  <div id="patternOutput"></div>
</div>

Note: Loops are powerful but can freeze your browser if you create an infinite loop. Always ensure your loop will end!