Chapter 7 Cheatsheet: Loops
This cheatsheet summarizes the iteration and looping mechanics covered in Chapter 7. Use it as a quick reference when dealing with repeated code execution.
Standard for Loops
The classic C-style loop, ideal for executing logic a specific, known number of times using a counter variable.
// for (initialization; condition; increment)
for (let i = 0; i < 5; i++) {
console.log(i); // 0, 1, 2, 3, 4
}
while Loops
Ideal for scenarios where you do not know the exact number of iterations beforehand, such as traversing a linked list or waiting for a specific threshold. Runs endlessly as long as the condition evaluates to true.
let balance = 100;
while (balance > 0) {
balance -= 10;
}
Loop Control Keywords
break
Immediately terminates the loop and escapes entirely. Required to safely escape an infinite loop.
for (let i = 0; ; i++) {
if (i === 10) break; // Exits at 10
}
continue
Immediately skips the remainder of the current iteration and proceeds to the next cycle of the loop.
for (let i = 0; i < 5; i++) {
if (i === 2) continue; // Skips 2
console.log(i); // 0, 1, 3, 4
}
for...in Loops
Used strictly for iterating over the string keys (properties) of an Object. Use bracket notation obj[key] to dynamically retrieve the associated value.
const settings = { theme: "dark", notifications: true };
for (const key in settings) {
console.log(key, settings[key]);
}
// "theme dark"
// "notifications true"