Overview
Loops are control flow structures that repeat a block of code as long as a specified condition is met. They are essential for processing collections of data or performing repetitive tasks without writing the same code multiple times.
Core Concepts
- Iteration: A single pass through the loop’s body.
- Loop Types:
- For Loop: Best when the number of iterations is known (counter-based).
- While Loop: Best when the loop should run as long as a condition is true, and the number of iterations is unknown.
- Do-While Loop: Similar to while, but guarantees the code block runs at least once.
- For-Each / For-Of: Specialized loops for iterating over collections (arrays, maps, sets).
- Control Keywords:
- Break: Immediately terminates the loop.
- Continue: Skips the current iteration and moves to the next one.
Code Examples
// Traditional For Loop
for (let i = 0; i < 5; i++) {
console.log(`Iteration ${i}`);
}
// While Loop
let energy = 3;
while (energy > 0) {
console.log("Working...");
energy--;
}
// For-Of Loop (Arrays)
const colors = ["Red", "Green", "Blue"];
for (const color of colors) {
console.log(color);
}
Use Cases
- Data Processing: Summing values in an array or filtering a list.
- Polling: Checking a resource (like an API or a file) until it becomes available.
- Game Loops: A continuous loop that updates game state and renders the frame.
Gotchas
- Infinite Loops: Occurs when the exit condition is never met (e.g., forgetting to increment the counter), causing the program to hang or crash.
- Off-by-One Errors: Iterating one time too many or too few (e.g., using
<=instead of<when indexing an array). - Modifying Collections during Iteration: Removing items from an array while looping over it can cause elements to be skipped or index-out-of-bounds errors.
