Syntax
for (init; condition; step) { }
while (condition) { }
do { } while (condition);Examples
for Loop
The classic counting loop.
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// Looping over an array by index
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}while Loop
Looping based on a condition, checked before each pass.
let count = 0;
while (count < 3) {
console.log(count);
count++;
}
// 0, 1, 2do...while Loop
A loop that always executes at least once, since the condition is checked after.
let attempts = 0;
do {
console.log(`Attempt ${attempts + 1}`);
attempts++;
} while (attempts < 3);
// Runs at least once even if the condition starts false
let x = 10;
do {
console.log("This runs once even though x is not < 5");
} while (x < 5);Best practices
- Use for...of instead of a classic for loop when you just need each value, not the index
- Use while when the number of iterations is not known ahead of time and depends on a changing condition
- Use do...while specifically when the loop body must run at least once regardless of the condition
- Always ensure the loop condition will eventually become false, to avoid accidental infinite loops
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification