WHAT'S NEW
TypeScript · Lesson 04 of 11

Mastering Loops

Why write the same instructions again and again? Learn to repeat tasks efficiently using loops, control when repetition stops, and build smarter TypeScript programs.

for Loops while Loops do…while break & continue
● ● ●   loops.ts
for (let i: number = 1;
     i <= 3; i++) {
  console.log(
    `Hello, Moe! ${i}`
  );
}
CONSOLE OUTPUT
> Ready to run…
01 / Understanding Repetition

Why Do We Need Loops?

Imagine you’re building a game and want to display a countdown from five to one. You could write five separate console.log() statements, but what if you needed to count down from one hundred?

A loop repeats a set of instructions while a condition is satisfied. It saves time, reduces duplicated code, and makes programs easier to maintain.

Without a loop
console.log("Hello, Moe! 1");
console.log("Hello, Moe! 2");
console.log("Hello, Moe! 3");

We can achieve the same result using just one console.log() inside a loop.

02 / For Loops

Repeat a Known Number of Times

A for loop is useful when you know how many repetitions you need. It combines a starting value, a condition, and an update into one statement.

for-loop.ts
for (let i: number = 1; i <= 3; i++) {
  console.log("Hello, Moe! " + i);
}
Console Output:
Hello, Moe! 1 Hello, Moe! 2 Hello, Moe! 3

How It Works

  1. let i: number = 1 initializes the counter.
  2. i <= 3 checks whether the loop should continue.
  3. The instructions inside the braces execute.
  4. i++ increases the counter by one.
  5. The condition is checked again before the next repetition.
Remember: i++ is shorthand for increasing i by one. When the condition becomes false, the loop stops.
03 / While Loops

Repeat While a Condition Is True

A while loop checks its condition before every repetition. It’s useful when you don’t necessarily know in advance how many times the instructions will need to run.

while-loop.ts
let level: number = 1;

while (level <= 3) {
  console.log("Moe reached level " + level);
  level++;
}
Console Output:
Moe reached level 1 Moe reached level 2 Moe reached level 3

The loop stops when level becomes 4 because 4 <= 3 is false.

Important: Make sure something can eventually cause the condition to become false. Otherwise, your loop may run indefinitely.
04 / Do…While Loops

Run the Instructions at Least Once

A do...while loop is similar to a while loop, but it checks the condition after running its instructions.

do-while.ts
let attempts: number = 1;

do {
  console.log("Attempt " + attempts);
  attempts++;
} while (attempts <= 3);
Console Output:
Attempt 1 Attempt 2 Attempt 3

Even if the condition starts out false, the body executes once. That makes do...while useful for tasks that must happen before you decide whether to repeat them.

05 / Break

Stop a Loop Early

Sometimes you want to stop repeating instructions before the loop’s normal condition becomes false. Use break to exit the loop immediately.

break.ts
for (let number: number = 1; number <= 10; number++) {
  if (number === 4) {
    break;
  }

  console.log(number);
}
Console Output:
1 2 3

When number reaches 4, the break statement ends the loop. The number 4 is never printed.

06 / Continue

Skip One Repetition

Unlike break, which stops the entire loop, continue skips the remainder of the current repetition and proceeds to the next one.

continue.ts
for (let number: number = 1; number <= 5; number++) {
  if (number === 3) {
    continue;
  }

  console.log(number);
}
Console Output:
1 2 4 5

Number 3 is skipped, but the loop continues with 4 and 5.

Quick comparison: break means “stop the loop.” continue means “skip this repetition.”
07 / Looping Backwards

Create a Countdown

Loops don’t always count upward. By starting at a larger number and decreasing the counter, you can create a countdown.

countdown.ts
for (let seconds: number = 5; seconds >= 1; seconds--) {
  console.log("Launching in " + seconds);
}

console.log("Liftoff, Moe!");
Console Output:
Launching in 5 Launching in 4 Launching in 3 Launching in 2 Launching in 1 Liftoff, Moe!

The seconds-- expression decreases the counter by one after each repetition.

08 / Loops and Functions

Make Repetition Reusable

You can place a loop inside a function to create a reusable tool. TypeScript lets you specify how many times the loop should run.

repeat-greeting.ts
function repeatGreeting(
  name: string,
  times: number
): void {
  for (let i: number = 1; i <= times; i++) {
    console.log(`Hello, ${name}! (${i})`);
  }
}

repeatGreeting("Moe", 3);
Console Output:
Hello, Moe! (1) Hello, Moe! (2) Hello, Moe! (3)

This combines what you learned in Lesson 03 with loops. Change the name or number of repetitions without rewriting the function.

09 / Common Loop Mistakes

Keep Your Loops Under Control

Two common mistakes are forgetting to update a counter and using the wrong comparison operator.

An off-by-one mistake
// Prints 1, 2, 3, and 4
for (let i = 1; i <= 4; i++) {
  console.log(i);
}

// Prints only 1, 2, and 3
for (let i = 1; i < 4; i++) {
  console.log(i);
}

The difference between < and <= changes the number of repetitions.

Sandbox safety: The editor below includes a loop-iteration guard to interrupt excessively long loops. This is a teaching safeguard, not a substitute for testing code in a properly isolated development environment.
🚀 mC0de Challenge

Build Moe’s Countdown Generator

Use a typed TypeScript function and a loop to create a personalized countdown.

Your Mission

  1. Change the developer variable to your preferred name.
  2. Change the start value to a different positive number.
  3. Use the for loop to count down to 1.
  4. Print a personalized launch message after the loop finishes.
  5. Run your code and check the countdown.
Extra challenge: Modify the loop to skip the number 3 using continue. Then try passing a string as the countdown’s numeric argument and observe the type error.
💻 Interactive TypeScript Sandbox

Create Your Countdown!

Edit the TypeScript, then run it to see the output. Use Load Solution if you want to compare your work with a completed example.

Console Output
Lesson 04 Recap

What You’ve Learned

You’re Making TypeScript Work Smarter!

You can now:

  • Explain why loops help reduce repeated code.
  • Write a for loop with a counter and condition.
  • Use while and do...while loops.
  • Stop a loop early with break.
  • Skip a repetition using continue.
  • Build countdowns and reusable looping functions.
  • Recognize common off-by-one and infinite-loop mistakes.

Next up: Arrays — learn how to store collections of values and use loops to work with them!

Your Learning Journey

0 / 11 Completed

Keep going! Every completed lesson brings you closer to building reliable applications with TypeScript.

🎉

You’re Getting the Hang of It!

You’ve learned how to repeat instructions with for, while, and do…while loops, control repetition with break and continue, and combine loops with TypeScript functions. Great work!

PIX0
</> {} JS 01
0101 </> CSS JS HTML PIX0 const {} 1010 async mC0de function return 0101 <div> 1010 PIX0 CSS JS HTML const {} 0101 mC0de
PIX0 // WORLD OF CODE
PIX0 IS PREPARING SOMETHING AWESOME FOR YOU 0%