JavaScript Loops
Loops offer a quick and easy way to do something repeatedly. Without loops, processing an array of 1,000 items would require 1,000 lines of identical code.
The for Loop
The for loop is the most common and concise way to write a loop when you know exactly how many times you want it to run. It groups the initialization, condition, and increment all on one line.
console.log("Iteration number " + i);
}
The while Loop
The while loop executes its statements as long as a specified condition evaluates to true. It is ideal for situations where you don't know beforehand how many times the loop needs to run (for example, reading data until a file ends).
while (n < 3) {
console.log(n);
n++; // CRITICAL: Without this, it's an infinite loop!
}
Control Flow: break & continue
Sometimes you need to alter the loop's natural flow:
- Break: Completely exits the loop, moving code execution to the next line after the loop structure.
- Continue: Skips the rest of the current iteration and jumps immediately back up to evaluate the condition for the next iteration.
The Infinite Loop Danger+
An infinite loop occurs when a loop's condition always evaluates to true. It will run endlessly, consuming all available CPU and memory resources until the browser tab crashes. Always double-check your increment logic inside while loops!
