intermediate
Step 8 of 20
Loops
JavaScript Programming
Loops
Loops let you execute code repeatedly, which is essential for processing arrays, generating sequences, waiting for conditions, and iterating over data structures. JavaScript provides several loop constructs: the traditional for loop, while and do...while loops, and modern iteration methods like for...of and for...in. Each has its ideal use case, and choosing the right one makes your code clearer and more efficient.
For Loop
// Classic for loop
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
// Iterating over an array
const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
console.log(`${i + 1}. ${fruits[i]}`);
}
// Counting backwards
for (let i = 10; i > 0; i--) {
console.log(i);
}
// Step by 2
for (let i = 0; i < 20; i += 2) {
console.log(i); // 0, 2, 4, ..., 18
}
for...of and for...in
// for...of — iterate over VALUES of an iterable
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}
// Works with strings
for (const char of "Hello") {
console.log(char); // H, e, l, l, o
}
// Works with Maps and Sets
const map = new Map([["a", 1], ["b", 2]]);
for (const [key, value] of map) {
console.log(`${key}: ${value}`);
}
// for...in — iterate over KEYS/properties of an object
const person = { name: "Alice", age: 30, city: "NYC" };
for (const key in person) {
console.log(`${key}: ${person[key]}`);
}
// Warning: for...in on arrays gives string indices, not values
const arr = [10, 20, 30];
for (const index in arr) {
console.log(typeof index); // "string" — not a number!
}
// Use for...of for arrays instead
// entries() for index + value
for (const [index, color] of colors.entries()) {
console.log(`${index}: ${color}`);
}
While and Do...While
// While — check condition before each iteration
let count = 0;
while (count < 5) {
console.log(`Count: ${count}`);
count++;
}
// Do...while — executes at least once
let input;
do {
input = prompt("Enter 'quit' to exit:");
console.log(`You entered: ${input}`);
} while (input !== "quit");
// Practical: polling pattern
async function waitForResult(checkFn, interval = 1000, maxAttempts = 10) {
let attempts = 0;
while (attempts < maxAttempts) {
const result = await checkFn();
if (result) return result;
await new Promise(r => setTimeout(r, interval));
attempts++;
}
throw new Error("Timeout");
}
Loop Control
// break — exit the loop
for (let i = 0; i < 100; i++) {
if (i > 5) break;
console.log(i); // 0, 1, 2, 3, 4, 5
}
// continue — skip to next iteration
for (let i = 0; i < 10; i++) {
if (i % 2 === 0) continue;
console.log(i); // 1, 3, 5, 7, 9
}
// Labeled loops (for nested loop control)
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}`);
}
}
// 0,0 0,1 0,2 1,0 (stops at 1,1)
// forEach — array method (no break/continue)
const numbers = [1, 2, 3, 4, 5];
numbers.forEach((num, index) => {
console.log(`Index ${index}: ${num}`);
});
// Note: you cannot break out of forEach — use for...of if you need break
Choosing the Right Loop
// Use for...of for arrays and iterables (MOST COMMON)
for (const item of myArray) { /* ... */ }
// Use for...in for object properties
for (const key in myObject) { /* ... */ }
// Use classic for when you need the index or custom stepping
for (let i = arr.length - 1; i >= 0; i--) { /* reverse */ }
// Use while for condition-based loops
while (queue.length > 0) { /* process queue */ }
// Use array methods for transformations (most idiomatic)
const result = arr.filter(x => x > 5).map(x => x * 2);
Pro tip: Preferfor...ofoverfor...infor arrays, and array methods (map,filter,forEach) over traditional loops when you are transforming data. If you need to break out early, usefor...ofwithbreak— you cannot break out offorEach. Usefor...inonly for iterating over object properties.
Key Takeaways
- Use
for...ofto iterate over array values, strings, Maps, and Sets — it is the most readable for iterables. - Use
for...inonly for iterating over object properties (keys), never for arrays. breakexits the loop;continueskips to the next iteration; labeled loops allow breaking out of nested loops.forEachdoes not supportbreakorcontinue— usefor...ofwhen you need early termination.- Array methods like
map(),filter(), andreduce()are often more expressive than manual loops for data transformations.