Last updated

JavaScript For Loops

Definition: A loop repeats code. The classic for loop runs a set number of times using three parts: a start, a condition, and a step.

Example 1 — counting

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

Start i at 0; keep going while i < 5; add 1 each time. Prints 0 to 4.

Example 2 — looping an array by index

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

Example 3 — the cleaner for...of

for (let fruit of fruits) {
  console.log(fruit);
}

Example 4 — a running total

let nums = [10, 20, 30];
let total = 0;
for (let n of nums) {
  total += n;
}
console.log("Total:", total);

💡 Tip: i++ means "add 1 to i". Use for...of when you just want each item, and the classic for when you need the index.

Try it Yourself
Output

          
Ad · responsive