AnyCompiler

for Loops

for loops in TypeScript work exactly like JavaScript's. The classic for loop gives you full manual control over an index; for...of hands you each item directly.

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

for...of over a typed array

Looping over a typed array with for...of, the loop variable's type is inferred automatically from the array's element type — no annotation needed.

const fruits: string[] = ["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 running total of 1 through 5 (i.e., print 1, then 3, then 6, then 10, then 15 — each line is the sum so far).