For Loops

Updated · 7 min read
easyES2026javascriptloopsfor-loopinterview

A loop repeats a block of code. The for loop is used when you know, or can calculate, how many times to repeat: once for each grade from 9 to 12, once for each payment in a list, once for each month of the year. It keeps a counter variable, checks a condition before each round, and updates the counter after each round, all in one line.

In One Minute

  • for (let i = 0; i < n; i++) { ... } runs the body n times, with i going from 0 to n - 1.
  • The three parts: initialization (runs once), condition (checked before each round), update (runs after each round).
  • Loop over an array by index with i < list.length. For plain "each item" loops, for...of (later in this chapter) is simpler.
  • Declare the counter with let, never var: each round then gets its own copy of i.

The for Loop

Syntax

syntax.js
for (initialization; condition; update) {
  // body: runs while condition is truthy
}
PartRunsTypical code
InitializationOnce, before the first roundlet i = 0
ConditionBefore every round; the loop stops when it is falsyi < 5
BodyOnce per roundyour code
UpdateAfter every roundi++

Example

for.js▶ Try it
for (let grade = 9; grade <= 12; grade++) {
  console.log(`Grade ${grade}`);
}
console.log("Done");
Output
Grade 9
Grade 10
Grade 11
Grade 12
Done

Explanation: grade starts at 9. Before each round, JavaScript checks grade <= 12; if true, it runs the body, then grade++. When grade becomes 13, the condition is false, the loop ends, and the program continues with "Done".

Counting in Other Steps

The update can be any expression. Count down, or count in steps:

steps.js▶ Try it
for (let i = 3; i >= 1; i--) {
  console.log(`Reminder ${i}`);
}
 
let months = "";
for (let month = 1; month <= 12; month += 3) {
  months += month + " ";
}
console.log("Quarter starts:", months);
Output
Reminder 3
Reminder 2
Reminder 1
Quarter starts: 1 4 7 10

Looping Through an Array

Arrays are indexed from 0 to length - 1, which matches the i < length pattern exactly:

array-loop.js▶ Try it
const fees = [120, 85, 45, 200];
let total = 0;
 
for (let i = 0; i < fees.length; i++) {
  console.log(`Fee ${i + 1}: $${fees[i]}`);
  total += fees[i];
}
console.log(`Total: $${total}`);
Output
Fee 1: $120
Fee 2: $85
Fee 3: $45
Fee 4: $200
Total: $450

Use an index-based for when you need the index, need to skip or step through items, or need to loop backwards. When you only need each item, for...of is shorter, and array methods such as map and filter (in the arrays chapter) are often better still.

Nested Loops

A loop inside a loop runs the inner loop completely for each round of the outer one. Nested loops build tables:

nested.js▶ Try it
const students = ["Navika", "Srihitha"];
const terms = ["Fall", "Spring"];
 
for (let s = 0; s < students.length; s++) {
  for (let t = 0; t < terms.length; t++) {
    console.log(`${students[s]} - ${terms[t]}`);
  }
}
Output
Navika - Fall
Navika - Spring
Srihitha - Fall
Srihitha - Spring

The body runs 2 × 2 = 4 times.

In Practice

The Fee Tracker prints a fee table for grades 9 to 12. Fees rise $15 per grade from a base of $400:

fee-table.js▶ Try it
const BASE = 400;
const STEP = 15;
 
console.log("Grade | Term fee");
for (let grade = 9; grade <= 12; grade++) {
  const fee = BASE + (grade - 9) * STEP;
  console.log(`${String(grade).padStart(5)} | $${fee}`);
}
Output
Grade | Term fee
    9 | $400
   10 | $415
   11 | $430
   12 | $445

padStart(5) adds spaces on the left so the numbers line up under "Grade"; the string methods lesson explains it.

Common Mistakes

Off by one. i <= list.length reads past the end. Use i < list.length.

Changing the counter inside the body. i++ in both the update and the body skips items. Change the counter in one place.

An update that never reaches the end. for (let i = 0; i < 10; i--) counts the wrong way and never stops. Make sure the update moves toward the condition becoming false.

Using var for the counter. It leaks out of the loop and is shared between rounds. Use let.

Under the Hood

Before 2015, loop counters were declared with var. A var has one variable for the whole function, shared by every round. That causes a famous bug when the loop schedules work for later:

let-loop.js▶ Try it
for (let i = 1; i <= 3; i++) {
  setTimeout(() => console.log("let:", i), 0);
}
Output
let: 1
let: 2
let: 3

Explanation: the timers run after the loop has finished. With var, all three functions look at the same i, which is 4 by then. With let, the specification creates a fresh binding of i for every round and copies the current value into it, so each function remembers its own i. This per-round copy is why let in a for loop "just works", and it is the first example of a closure, which has a lesson of its own later.

Interview Corner

Why does a for loop with var and setTimeout print the same number every time?

var is function-scoped, so all callbacks close over one shared i, which holds its final value when the timers run. let creates a new binding per iteration (the specification copies the value into a fresh environment each round), so each callback sees its own value. The pre-2015 fix was an IIFE that captured i as a parameter.

When would you use a classic for loop instead of for...of or array methods?

When you need the index, a step other than 1, reverse order, early exit with break on an index condition, or to mutate the array by index while looping. For plain iteration, for...of; for transformations, map, filter and reduce.

Practice

Challenge: Print the multiplication table for 5 from 5 x 1 = 5 to 5 x 5 = 25, then print the sum of all five results.

Show solution
table.js▶ Try it
let sum = 0;
for (let i = 1; i <= 5; i++) {
  const result = 5 * i;
  console.log(`5 x ${i} = ${result}`);
  sum += result;
}
console.log("Sum:", sum);
Output
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
Sum: 75

Quick check: For loops

3 questions
1How many times does for (let i = 0; i < 4; i++) run its body?
2When is the condition of a for loop checked?
3Why should the loop counter be declared with let?

Key Takeaways

LoopPattern
Count upfor (let i = 0; i < n; i++)
Count downfor (let i = n - 1; i >= 0; i--)
Step by 3for (let i = 0; i < n; i += 3)
Array by indexfor (let i = 0; i < arr.length; i++)

Was this tutorial helpful?

Lesson 15 of 139