Control Flow in TypeScript - If, Else, and Switch Statements


Introduction

Control flow statements are essential in any programming language to make decisions and execute code conditionally. In TypeScript, you can use if, else, and switch statements to control the flow of your program. Let's explore these control flow constructs in TypeScript.


If and Else Statements

The if statement allows you to execute code conditionally based on a specified condition. You can also use else to define an alternative block of code to execute when the condition is not met.


Example:

let age: number = 18;
if (age >= 18) {
console.log("You are an adult.");
} else {
console.log("You are not yet an adult.");
}

Switch Statement

The switch statement allows you to evaluate an expression against multiple case values. It's often used when you have several conditions to check.


Example:

let day: string = "Monday";
let message: string;
switch (day) {
case "Monday":
message = "It's the start of the week.";
break;
case "Friday":
message = "It's almost the weekend!";
break;
default:
message = "It's a regular day.";
}
console.log(message);

Nested Control Flow

You can nest if statements within other if statements or combine if and switch statements to create complex control flow logic.


Example:

let hour: number = 14;
if (hour >= 12) {
if (hour < 18) {
console.log("Good afternoon!");
} else {
console.log("Good evening!");
}
} else {
console.log("Good morning!");
}

Conclusion

Control flow statements are crucial in TypeScript for making decisions and executing code conditionally. Whether it's simple if-else statements or complex nested control flow, these constructs are powerful tools for controlling the flow of your programs. As you continue to learn TypeScript, you'll use these statements to build more sophisticated applications with conditional behavior.