The for Loop

Repeat code a set number of times.

Syntaxfor (let i = 0; i < n; i++) { ... }

The for loop repeats code a known number of times. It has three parts inside the parentheses:

  1. Initialization — runs once: let i = 0.
  2. Condition — checked before each pass: i < 5.
  3. Update — runs after each pass: i++.

Example

Try it yourself
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.

Example · js
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.

Example · js
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.

Example · js
for (let i = 10; i >= 0; i--) {
  console.log(i === 0 ? "Launch!" : i);
}

Discussion

  • Be the first to comment on this lesson.
The for Loop — JavaScript | SoundsCode