TypeScript Loops: for, while and for...of (and How to Stop an Infinite Loop)
November 6, 2026
Welcome to episode 7 of TypeScript from Zero, a series for complete beginners (no JavaScript needed). Welcome back to TypeScript from zero! Today: loops. A loop repeats code, so we do not have to write it again and again. A new file called loops.ts. Every code block below is the code from the video, ready to copy; run each file to see the output.
- All episodes are in the TypeScript from Zero playlist.
- Versions used: Node.js 26.13.0, npm 11.20.0, TypeScript 7.0.2.
Setup
We start in the terminal and open the project in VS Code:
$ touch loops.ts1. for
The for loop has three parts in the parentheses. Where to start, here i is one. When to keep going, while i is at most three. And what to do after each round, plus plus adds one. The block runs three times.
for (let i = 1; i <= 3; i++) {
console.log(i);
}$ node loops.ts2. while
The while loop only has a condition. It repeats while the condition is true. We count down from three, and each round we subtract one with minus minus.
let countdown = 3;
while (countdown > 0) {
console.log(countdown);
countdown--;
}$ node loops.ts3. for of
To go through every item of a list, we use for of. The list is called an array, and we will learn it properly in the next episode. Here it has three colors, and the loop gives us one color at a time.
const colors = ["red", "green", "blue"];
for (const color of colors) {
console.log(color);
}$ node loops.ts4. break
Two keywords change a loop. Continue skips the rest of this round, here when j is two. Break leaves the loop completely, here when j is four. So we only see one and three.
for (let j = 1; j <= 5; j++) {
if (j === 2) continue;
if (j === 4) break;
console.log(j);
}$ node loops.ts5. Forever
Now the classic bug. A while loop where we forgot to change n. The condition n below three stays true forever. We run it. It prints counting, and then nothing happens, and it never ends.
let n = 0;
console.log("Counting...");
while (n < 3) {
// forgot to change n
}
console.log("Done");$ node loops.ts6. Stop
Do not close the terminal. Press control C. That stops the running program. tsc could not warn us here, because it is not a type error. We have to think.
7. Fix
The fix: change n inside the loop, with n plus plus. Now after three rounds the condition is false, the loop ends, and the word Done is printed.
$ node loops.tsRecap
Today: the for loop for counting, the while loop for conditions, the for of loop for lists, continue and break, and control C when a loop never ends. Next episode: arrays.