The for loop is the classic way to repeat a block of code a specific number of times in JavaScript. It's one of the first control structures every developer learns, and it's still the right tool whenever you need full control over exactly how many times something runs and how the counter changes.

Basic for Loop Syntax

A for loop has three parts separated by semicolons: an initializer (runs once, before the loop starts), a condition (checked before every iteration), and an increment (runs after every iteration).

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

Output:

1
2
3
4
5

Here, i starts at 1, the loop keeps running as long as i <= 5, and i increases by 1 after each pass. Once i becomes 6, the condition is false and the loop stops.

Iterating Over an Array by Index

The most common real-world use of a for loop is walking through an array by its index, which also gives you access to the position of each element — something a forEach() or for...of loop doesn't give you as directly.

const fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
  console.log(`${i}: ${fruits[i]}`);
}

Output:

0: apple
1: banana
2: cherry

Nested for Loops

A loop inside another loop is common for working with grids, tables, or comparing every element against every other element. The inner loop completes fully for each single pass of the outer loop.

for (let row = 1; row <= 3; row++) {
  let line = "";
  for (let col = 1; col <= 3; col++) {
    line += `(${row},${col}) `;
  }
  console.log(line);
}

Output:

(1,1) (1,2) (1,3)
(2,1) (2,2) (2,3)
(3,1) (3,2) (3,3)

For 3x3, that's 9 total inner iterations. Be careful with deeply nested loops over large arrays — complexity grows quickly, which matters once you start thinking about performance.

Once you're comfortable with for, it's worth learning its close relatives: the while loop for when you don't know the iteration count in advance, and for...in vs for...of for cleaner iteration over objects and iterables.