TypeScript - While Loop: A Beginner's Guide

Hello, aspiring programmers! Today, we're going to dive into one of the fundamental concepts in programming: the while loop. As your friendly neighborhood computer teacher, I'm excited to guide you through this journey. Don't worry if you're new to coding – we'll start from the basics and work our way up. So, grab a cup of coffee (or your favorite beverage), and let's get looping!

TypeScript - While Loop

What is a While Loop?

Before we jump into the nitty-gritty, let's understand what a while loop is. Imagine you're playing a game where you need to keep rolling a dice until you get a six. You wouldn't know beforehand how many times you'd need to roll, right? This is exactly where a while loop comes in handy in programming!

A while loop allows you to repeat a block of code as long as a certain condition is true. It's like telling your computer, "Hey, keep doing this until I tell you to stop!"

Syntax

Now, let's look at the syntax of a while loop in TypeScript:

while (condition) {
    // code to be executed
}

It's pretty simple, isn't it? Here's what each part means:

  • while: This keyword tells TypeScript that we're starting a while loop.
  • condition: This is a boolean expression that's checked before each iteration of the loop. If it's true, the loop continues; if it's false, the loop stops.
  • { }: These curly braces contain the code that will be repeatedly executed as long as the condition is true.

Flow Diagram

To better understand how a while loop works, let's look at a flow diagram:

       ┌─────────────┐
       │   Start     │
       └─────┬───────┘
             │
             ▼
    ┌─────────────────┐
    │ Check condition │◄─────┐
    └─────────┬───────┘      │
              │              │
              ▼              │
         ┌────────┐          │
    ┌────│  True  │          │
    │    └────┬───┘          │
    │         │              │
    │         ▼              │
    │  ┌─────────────┐       │
    │  │ Execute code│       │
    │  └─────────────┘       │
    │         │              │
    │         └──────────────┘
    │    
    │    ┌────────┐
    └────►  False │
         └────┬───┘
              │
              ▼
       ┌─────────────┐
       │    End      │
       └─────────────┘

This diagram shows how the while loop continually checks the condition and executes the code block until the condition becomes false.

Example: While Loop

Let's dive into a practical example. We'll create a program that counts down from 5 to 1:

let countdown: number = 5;

while (countdown > 0) {
    console.log(countdown);
    countdown--;
}

console.log("Blast off!");

Let's break this down:

  1. We start by declaring a variable countdown and set it to 5.
  2. The while loop checks if countdown is greater than 0.
  3. If it is, it prints the current value of countdown.
  4. Then, it decreases countdown by 1 using the -- operator.
  5. This process repeats until countdown is no longer greater than 0.
  6. Finally, it prints "Blast off!" once the loop ends.

When you run this code, you'll see:

5
4
3
2
1
Blast off!

Isn't that cool? It's like we've created our own little rocket launch countdown!

While Loop with a Break Statement

Sometimes, you might want to exit a loop early based on a certain condition. That's where the break statement comes in handy. It's like having an emergency exit in your loop!

Let's modify our countdown example:

let countdown: number = 10;

while (countdown > 0) {
    console.log(countdown);
    countdown--;

    if (countdown === 5) {
        console.log("We're halfway there!");
        break;
    }
}

console.log("Countdown interrupted!");

In this example, we start the countdown from 10, but we interrupt it when we reach 5. The output will be:

10
9
8
7
6
5
We're halfway there!
Countdown interrupted!

The break statement allows us to exit the loop prematurely when a specific condition is met.

While Loop vs. For Loop

Now, you might be wondering, "Why use a while loop when we have for loops?" Great question! Let's compare them:

While Loop For Loop
Used when the number of iterations is unknown Used when the number of iterations is known
Condition is checked at the beginning of each iteration Initialization, condition, and update are all in one line
Can be used to create infinite loops more easily Typically used for finite loops
More flexible structure More compact structure

Here's a quick example to illustrate:

// While loop
let i: number = 0;
while (i < 5) {
    console.log(i);
    i++;
}

// Equivalent for loop
for (let j: number = 0; j < 5; j++) {
    console.log(j);
}

Both of these loops will print numbers from 0 to 4. The while loop is more flexible, as you can modify the loop variable (i) in more complex ways inside the loop body. The for loop, on the other hand, is more concise when you know exactly how many times you want to iterate.

Conclusion

And there you have it, folks! We've journeyed through the land of while loops in TypeScript. From understanding the basic syntax to exploring break statements and comparing with for loops, you're now equipped with the knowledge to use while loops effectively in your code.

Remember, programming is like learning to ride a bicycle – it might seem wobbly at first, but with practice, you'll be zooming around in no time! So, don't be afraid to experiment with while loops in your own projects. Try creating a guessing game, or maybe a program that calculates compound interest until a certain amount is reached.

Happy coding, and may your loops always terminate!

Credits: Image by storyset