A JavaScript for loop repeats a block of code a specific number of times when the number of iterations is known, using the syntax for (initialization; condition; afterthought) { // code block }. The initialization runs once before the loop starts, the condition is evaluated before each iteration to determine if the loop continues, and the afterthought (typically an increment) executes after each iteration.
Standard For Loop Syntax and Execution
The loop executes the code block as long as the condition evaluates to true, following this sequence:
The initialization expression (e.g.,
let i = 0) runs once to set up a counter or variable.The condition expression (e.g.,
i < 5) is checked; if false, the loop terminates immediately.The statement block runs.
The afterthought expression (e.g.,
i++) increments the counter before returning to the condition check.
for (let i = 0; i < 5; i++) {
console.log("The number is " + i);
}Alternative Loop Types
While the standard for loop is ideal for counting, other iteration methods serve different purposes:
for...of: Iterates over the values of iterable objects like arrays, strings, Maps, and Sets.for...in: Iterates over the enumerable properties (keys) of an object.while: Repeats code as long as a specified condition remains true, checking the condition before execution.do...while: Similar towhile, but guarantees the code block executes at least once before checking the condition.
| Loop Type | Best Use Case | Iterates Over |
for | Known number of iterations | Values and expressions |
for...of | Iterating array elements or iterable values | Values of iterable objects |
for...in | Iterating object properties | Object keys/properties |
while | Unknown iterations based on a condition | Condition evaluation |
do...while | Ensuring at least one execution | Condition evaluation |
Control flow statements like break (to exit the loop) and continue (to skip the current iteration) can be used within any loop type to modify execution flow.