Loops in JavaScript
"for, while, for...of, and for...in — and when to reach for each one."
2 min read
JavaScript has several ways to repeat code, and picking the right one makes the intent of a loop obvious at a glance.
The classic for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0 1 2 3 4
}Three parts, separated by semicolons: an initializer (let i = 0), a condition checked before each iteration (i < 5), and an update that runs after each iteration (i++). Use it when you need the index itself, or fine control over how the loop advances.
while and do...while
let n = 0;
while (n < 3) {
console.log(n);
n++;
}while checks its condition before each iteration and may run zero times. do...while checks after, guaranteeing at least one run:
let attempts = 0;
do {
attempts++;
} while (attempts < 0); // condition is false, but the body still ran oncefor...of — iterating values
for...of walks any iterable (arrays, strings, Maps, Sets) and gives you each value directly, with no index bookkeeping:
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}This is the go-to loop for arrays when you just need each element — it's shorter and harder to get wrong than a manual index-based for.
for...in — iterating keys
for...in walks the enumerable property keys of an object:
const user = { name: "Ada", age: 36 };
for (const key in user) {
console.log(key, user[key]); // name Ada / age 36
}for...in also works on arrays (it iterates indexes as strings), but avoid it there — it doesn't guarantee order, includes inherited enumerable properties, and gives you string indexes instead of the values themselves. Use for...of (or array methods like forEach, covered later) for arrays, and reserve for...in for plain objects.
break and continue
Both work in any loop: break exits the loop entirely, continue skips to the next iteration.
for (let i = 0; i < 10; i++) {
if (i === 3) continue; // skip 3
if (i === 6) break; // stop at 6
console.log(i);
}
// Logs: 0 1 2 4 5With control flow in place, the course moves into functions — how JavaScript packages up reusable blocks of logic.