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


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.


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.


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

Nested Control Flow

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


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


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.