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 (let i: number = 1;
i <= 3; i++) {
console.log(
`Hello, Moe! ${i}`
);
}
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.
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.
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 (let i: number = 1; i <= 3; i++) {
console.log("Hello, Moe! " + i);
}How It Works
let i: number = 1initializes the counter.i <= 3checks whether the loop should continue.- The instructions inside the braces execute.
i++increases the counter by one.- The condition is checked again before the next repetition.
i++ is shorthand for increasing i by one. When the condition becomes false, the loop stops.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.
let level: number = 1;
while (level <= 3) {
console.log("Moe reached level " + level);
level++;
}The loop stops when level becomes 4 because 4 <= 3 is false.
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.
let attempts: number = 1;
do {
console.log("Attempt " + attempts);
attempts++;
} while (attempts <= 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.
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.
for (let number: number = 1; number <= 10; number++) {
if (number === 4) {
break;
}
console.log(number);
}When number reaches 4, the break statement ends the loop. The number 4 is never printed.
Skip One Repetition
Unlike break, which stops the entire loop, continue skips the remainder of the current repetition and proceeds to the next one.
for (let number: number = 1; number <= 5; number++) {
if (number === 3) {
continue;
}
console.log(number);
}Number 3 is skipped, but the loop continues with 4 and 5.
break means “stop the loop.” continue means “skip this repetition.”Create a Countdown
Loops don’t always count upward. By starting at a larger number and decreasing the counter, you can create a countdown.
for (let seconds: number = 5; seconds >= 1; seconds--) {
console.log("Launching in " + seconds);
}
console.log("Liftoff, Moe!");The seconds-- expression decreases the counter by one after each repetition.
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.
function repeatGreeting(
name: string,
times: number
): void {
for (let i: number = 1; i <= times; i++) {
console.log(`Hello, ${name}! (${i})`);
}
}
repeatGreeting("Moe", 3);This combines what you learned in Lesson 03 with loops. Change the name or number of repetitions without rewriting the function.
Keep Your Loops Under Control
Two common mistakes are forgetting to update a counter and using the wrong comparison operator.
// 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.
Build Moe’s Countdown Generator
Use a typed TypeScript function and a loop to create a personalized countdown.
Your Mission
- Change the
developervariable to your preferred name. - Change the
startvalue to a different positive number. - Use the
forloop to count down to 1. - Print a personalized launch message after the loop finishes.
- Run your code and check the countdown.
continue. Then try passing a string as the countdown’s numeric argument and observe the type error.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.
Preparing TypeScript sandbox…
What You’ve Learned
You’re Making TypeScript Work Smarter!
You can now:
- Explain why loops help reduce repeated code.
- Write a
forloop with a counter and condition. - Use
whileanddo...whileloops. - 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 CompletedKeep 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!
