JavaScript for Loops

Repeat Code With a Counter

JavaScript for Loops

The classic `for` loop runs code while a counter is in range. Three parts: init, condition, step.

4 min read Level 1/5 #for#loops#iteration
What you'll learn
  • Write a `for` loop with init, condition, step
  • Iterate a fixed number of times
  • Use `let` for the loop variable

A for loop runs a block of code repeatedly while a condition holds. The classic form has three parts inside the parentheses:

for (init; condition; step) {
  // body
}
Count from 0 to 4 script.js
for (let i = 0; i < 5; i++) {
  console.log(i);
}
// 0
// 1
// 2
// 3
// 4
▶ Preview: console

What happens:

  1. Init: let i = 0 runs once before the loop.
  2. Condition: i < 5 is checked. If true, run the body.
  3. Body: console.log(i).
  4. Step: i++ runs after each iteration.
  5. Repeat from step 2.

Walking Through an Array

Iterate by index script.js
const fruits = ["apple", "banana", "grape"];

for (let i = 0; i < fruits.length; i++) {
  console.log(`${i}: ${fruits[i]}`);
}
// "0: apple"
// "1: banana"
// "2: grape"
▶ Preview: console

This works but is verbose. For “do something with each item”, for..of (next lesson) reads better. Use the indexed for when you need the index, or when you’re iterating numerically.

Counting Down

Count down script.js
for (let i = 10; i > 0; i--) {
  console.log(i);
}
console.log("Liftoff!");
▶ Preview: console

Skipping Values

Step by 2 script.js
for (let i = 0; i <= 10; i += 2) {
  console.log(i);
}
// 0, 2, 4, 6, 8, 10
▶ Preview: console

Always Use let for the Counter

let i = 0 gives the counter block scope — each loop iteration effectively gets its own i. This avoids a class of bugs that plagued JavaScript before ES6.

Infinite Loops

If your condition never becomes false, you’ve got an infinite loop — the browser will hang.

// Will run forever:
// for (let i = 0; i < 10; i--) { … }
//   ← oops, i goes DOWN, never reaches 10

// Will run forever:
// for (let i = 0; ; i++) { … }
//   ← no condition

If your editor or browser tab freezes, this is the usual suspect.

Up Next

For iterating arrays and other collections, for..of is the modern idiom.

JavaScript for..of →