Lesson 19 +10 XP

JavaScript For Loop

JavaScript For Loop

A loop runs the same code over and over. The for loop is the most common.

The for syntax

for (statement 1; statement 2; statement 3) {
  // code to run each time
}
  • statement 1: runs once at the start (the counter).
  • statement 2: the condition checked before each loop.
  • statement 3: runs after each loop (usually increment).

A counting example

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

This prints 0, 1, 2, 3, 4.

Loop through an array

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

Breaking it down

  1. let i = 0 starts the counter.
  2. i < 5 is checked; if true, the block runs.
  3. i++ adds 1 after each run.
  4. When i reaches 5, the condition is false and the loop stops.

TL;DR

  • for loops repeat code a set number of times.
  • Three parts: start, condition, step.
  • Great for counting and looping through arrays.