Loops
8 min · TypeScript
Repeat work without writing it out a hundred times.
Enemy 1 of 5
This for loop counts i from 0 up to 2 and prints each number, so the code inside runs three times. Press Run to see 0, 1, 2.
Why this works
A for loop repeats a block of code so you don't have to write the same lines over and over. It has three parts inside the parentheses, separated by semicolons: a starting point, a condition to keep going, and a step to run after each pass.
This counts i from 0 while i is less than 3, adding 1 (i++) each time, so it runs exactly three times and prints 0, 1, 2. Typing the loop variable as number (let i: number = 0) is often optional here since TypeScript can infer it from the starting value 0, but writing it explicitly makes the intent unmistakable.