Conditional Statements and Loop Control in TypeScript

Introduction

Welcome! In this lesson, we're exploring special instructions in the TypeScript language: Conditional Statements, along with the break and continue statements. As we've learned, loops allow us to execute a block of code numerous times. By combining these loops with conditional statements and incorporating the useful break and continue instructions, we achieve more robust and efficient code. A key feature of TypeScript is its type-checking, which enhances the reliability of your conditions. Let's dive in!

The 'if' Statement

In TypeScript, the if statement triggers actions in our code based on a specific condition. Consider this straightforward example, where the if statement determines which message to print based on the value of temperature:

let temperature: number = 15;
if (temperature > 20) {
    console.log("Wear light clothes."); // This message will print if the temperature is over 20.
} else {
    console.log("Bring a jacket."); // This message will print otherwise.
}
// Output: Bring a jacket.

The "else if" Statement

We can evaluate multiple conditions using else if. This phrase means, "If the previous condition isn't true, then check this one":

let temperature: number = 15;

if (temperature > 30) {
    console.log("It's hot outside!"); // This will print if the temperature is over 30.
} else if (temperature > 20) {
    console.log("The weather is nice."); // This will print if the temperature is between 21 and 30.
} else {
    console.log("It might be cold outside."); // This will print if the temperature is 20 or below.
}
// Output: It might be cold outside.

The 'break' Statement

We use the break statement whenever we want to exit a loop prematurely once a condition is met:

const numbers: number[] = [1, 3, 7, 9, 12, 15];

for (let i: number = 0; i < numbers.length; i++) {
    if (numbers[i] % 2 === 0) {
        console.log("The first even number is: " + numbers[i]); // This prints the first even number.
        break; // This stops the loop after printing the first even number.
    }
    console.log("Number: " + numbers[i]);
}

// Output:
// Number: 1
// Number: 3
// Number: 7
// Number: 9
// The first even number is: 12
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