Mastering While Loops with TypeScript

Lesson Overview

Welcome to the world of iterations and loops. Let's dive into TypeScript's while loops! While loops are essential in programming because they allow code to be executed repeatedly while a certain condition remains true. They function similarly to an action that you repeat until a certain condition changes; for instance, cleaning a room until it's no longer messy. The while loop runs as long as the condition is met.

What are While Loops?

while loops in TypeScript are control flow statements that allow a block of code to be executed repeatedly while a given condition remains true. For instance, consider a situation where you keep playing outside while it's sunny. Here's what a while loop in TypeScript might look like:

let counter: number = 0; // Initialize with 0
while (counter < 5) { // Loop while counter is less than 5
    console.log(counter); // Print the counter
    counter++; // Increment the counter by 1 after each loop iteration
}
/*
Prints:
0
1
2
3
4
*/

In this example, we initialize a counter with an initial value of 0. The current counter value is then logged as long as its value is less than 5. Once the value reaches 5 or higher, the loop execution stops.

The Syntax of While Loops

A while loop in TypeScript comprises a condition and a body of code. If the condition is true, the code block (body) within the while statement is executed.

while (condition) { // Loop continues while the condition is true
    // block of code
}

Practical Examples with While Loops

Imagine the need to run a countdown from 5 to 1. This can conveniently be achieved using a while loop as follows:

let number: number = 5; // Initialize with 5

while (number >= 1) { // While number is at least 1
    console.log('Number is:', number); // Print the number
    number--; // Decrease the number by one after each iteration
}
/*
Prints:
Number is: 5
Number is: 4
Number is: 3
Number is: 2
Number is: 1
*/

Compound Conditions with While Loops

while loops in TypeScript can use compound conditions utilizing && (and) or || (or). For example, consider a scenario where you're saving up for a bike and want to stop saving once you hit your goal, or when winter starts, whichever comes first:

let savings: number = 0; // Starting savings
let isWinter: boolean = false; // Identifying the start of winter

while (savings < 100 && !isWinter) { // Continue while savings is less than 100 and it's not winter
    savings += 10; // Increase savings by 10
    console.log('Savings:', savings);

    // Simulate the changing of seasons
    if (savings === 50) { // When savings equals 50, winter starts
        isWinter = true;
    }
}
/*
Prints:
Savings: 10
Savings: 20
Savings: 30
Savings: 40
Savings: 50
*/
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal