Learn to repeat actions with for, while, do...while loops, and control loop flow with break and continue.
The for loop repeats a block of code a specific number of times. Its syntax has three parts:
for (initialization; condition; update) {
// code to repeat
}The most common pattern:
for (let i = 0; i < 5; i++) {
console.log('Iteration:', i);
}
// Output: 0, 1, 2, 3, 4You can use for loops to iterate over arrays by index:
const colors = ['red', 'green', 'blue'];
for (let i = 0; i < colors.length; i++) {
console.log(colors[i]);
}The while loop repeats a block of code as long as a condition is true. It checks the condition before each iteration:
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:
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.
Two keywords give you finer control over loop execution:
break — Immediately exits the loop entirely.
for (let i = 0; i < 100; i++) {
if (i === 5) break;
console.log(i);
}
// Output: 0, 1, 2, 3, 4continue — Skips the rest of the current iteration and moves to the next one.
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:
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);
}
}<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?