๐ŸŽ“ A1Learner
๐Ÿ”

JavaScript For Loop

The for loop repeats a block of code a counted number of times. Three parts in its header set the start, the condition, and the step.

The three parts

The header holds the start, the condition, and the step. The body logs the counter on each turn.

for (let i = 0; i < 3; i++) {
  console.log(i);
}

Counting up

The counter starts at 1 and stops after 5. The step adds 1 on each turn.

for (let i = 1; i <= 5; i++) {
  console.log(i);
}

Counting down

A step can count down instead of up. Here the step removes 2 on each turn.

for (let i = 10; i > 0; i -= 2) {
  console.log(i);
}

Example

const fruits = ["apple", "banana", "cherry"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

Key points

  • Start: the first part runs once before the loop begins.
  • Condition: the second part is checked before every turn.
  • Step: the third part runs after every turn.
  • The loop variable is a normal let variable.
  • The loop stops when the condition turns false.

In this example, the array holds three fruit names. The counter starts at 0, the first index. The condition compares the counter with the array length. Each turn logs the item at the current index. The loop stops when the counter reaches the length.

Note

One full run of the body is called an iteration.

Try it Yourself

Edit the code, then press Run.

Runs in your browser โ€” the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.

Exercise

In for (let i = 0; i < 5; i++), how many times does the body run?