Loops
for, while, for...of, for...in, and how to break and continue iteration.
What you'll learn
- The classic for loop and when to use it
- while and do...while loops
- for...of for iterating iterable values (arrays, strings)
- for...in for iterating object keys (and why to be careful)
- break and continue to control loop flow
Concept
The Classic for Loop
Use it when you need the index:
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
while and do...while
while checks the condition before each iteration. do...while checks it after, so the body always runs at least once:
let count = 3;
while (count > 0) {
console.log(count);
count--;
}
let n = 0;
do {
console.log("runs at least once");
} while (n > 0);
for...of — for values
for...of iterates over iterable values — arrays, strings, maps, sets. This is the modern, idiomatic way to loop through a collection:
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
for (const char of "Hello") {
console.log(char); // H, e, l, l, o
}
for...in — for keys (be careful!)
for...in iterates over enumerable property keys of an object. It is not meant for arrays — it can return indices as strings and include inherited properties:
const obj = { a: 1, b: 2, c: 3 };
for (const key in obj) {
console.log(key, obj[key]); // "a" 1, "b" 2, "c" 3
}
// Do NOT use for...in with arrays!
const arr = [10, 20, 30];
for (const i in arr) {
console.log(i); // "0", "1", "2" — strings, not numbers
}
Rule: for...of for arrays and strings (values), for...in for objects (keys).
break and continue
breakexits the loop entirely.continueskips the rest of the current iteration and moves to the next.
for (let i = 0; i < 10; i++) {
if (i === 3) continue; // skip 3
if (i === 7) break; // stop at 7
console.log(i); // 0, 1, 2, 4, 5, 6
}
Prefer Functional Methods
For arrays, map, filter, and reduce are often clearer than a manual loop. Reach for a for loop only when you need early break or index-based logic that the functional methods cannot express cleanly.
Example
// for...of — the modern way to iterate arrays
const tasks = ["design", "code", "test", "deploy"];
for (const task of tasks) {
console.log(`→ ${task}`);
}
// Classic for loop when you need the index
const numbers = [10, 20, 30, 40, 50];
for (let i = 0; i < numbers.length; i++) {
console.log(`index ${i}: ${numbers[i]}`);
}
// while loop for conditional repetition
let retries = 0;
const maxRetries = 3;
while (retries < maxRetries) {
console.log(`Attempt ${retries + 1}`);
retries++;
}
// break and continue
const scores = [85, 42, 90, 30, 88, 95];
let passed = 0;
for (const score of scores) {
if (score < 60) continue; // skip failing scores
passed++;
if (passed >= 3) break; // stop after 3 passing scores
console.log("Passed:", score);
}
// for...in for object keys
const config = { host: "localhost", port: 3000, debug: true };
for (const key in config) {
console.log(`${key} = ${config[key]}`);
}
Demonstrates for...of for array values, a classic indexed for loop, a while loop for retries, break/continue to filter and stop early, and for...in for object keys.
Try it
- Text Counter
Counting characters and words is a classic loop task.
- Line Deduplicator
Removing duplicates requires iterating and comparing lines.
Common mistakes
The mistake
Using for...in to iterate an array
The fix
for...in iterates over property keys (as strings) and can include inherited properties. Use for...of to iterate array values, or a classic for loop if you need indices.
The mistake
Creating an infinite while loop by forgetting to update the condition variable
The fix
Always make sure the loop variable changes inside the body so the condition eventually becomes false. Use a safety counter as a backup for complex conditions.
Related Resources
Related Cheatsheets
- JavaScript Cheatsheet
Loop syntax and iteration patterns reference.
Practice Loops
2 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.