The for Loop
Repeat code a set number of times.
Syntax
for (let i = 0; i < n; i++) { ... }The for loop repeats code a known number of times. It has three parts inside the parentheses:
- Initialization — runs once:
let i = 0. - Condition — checked before each pass:
i < 5. - Update — runs after each pass:
i++.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Render a fixed number of skeleton placeholder cards while product data is loading.
- Iterate over an array of form fields by index to build a validation summary.
- Generate numbered list items from 1 to N for a quiz question selector.
More examples
Basic counted for-loop
Runs the loop body five times, printing a numbered item label each iteration.
for (let i = 1; i <= 5; i++) {
console.log("Item " + i);
}Iterate array by index
Uses a for-loop index to access each product by position and print its number and name.
const products = ["Laptop", "Phone", "Tablet"];
for (let i = 0; i < products.length; i++) {
console.log(i + ": " + products[i]);
}Count down with decrement
Decrements the counter on each iteration to produce a countdown sequence ending with a launch message.
for (let i = 10; i >= 0; i--) {
console.log(i === 0 ? "Launch!" : i);
}
Discussion