AnyCompiler

for Loops

A for loop runs a block of code a set number of times, or once for every item in a collection. JavaScript has two flavors worth knowing: the classic for loop, and the more modern for...of.

for (let i = 0; i < 5; i++) {
  console.log(i);
}
Output
0
1
2
3
4

The classic for loop has three parts separated by semicolons: a starting value (let i = 0), a condition checked before every iteration (i < 5), and something that runs after every iteration (i++). It gives you full control, but it's easy to get an off-by-one error wrong.

Looping over an array with for...of

for...of hands you each item directly, without needing to track an index manually — closer to how Python's for loop works.

const fruits = ["apple", "banana", "cherry"];
for (const fruit of fruits) {
  console.log(fruit);
}
Output
apple
banana
cherry

Next: while loops — repeating based on a condition instead of a fixed collection.

Practice exercise

Use a for loop to print the numbers 1 through 5, each on its own line.