TypeScript Conditional Statements
Conditional statements are used to execute different code blocks based on different conditions. TypeScript supports the same conditional statements as JavaScript.
1. if Statement
The if statement is the most basic conditional control structure. It executes a code block when the specified condition is true.
Syntax
if (condition) {
// Code to execute when condition is true
}Example
let num: number = 10;
if (num > 0) {
console.log("The number is positive.");
}2. if...else Statement
The if...else statement executes one code block when the condition is true and another code block when the condition is false.
Syntax
if (condition) {
// Code to execute when condition is true
} else {
// Code to execute when condition is false
}Example
let temperature: number = 25;
if (temperature > 30) {
console.log("It's a hot day!");
} else {
console.log("The weather is pleasant.");
}3. if...else if...else Statement
When you need to check multiple conditions, you can use the if...else if...else structure. It tests each condition in order and executes the code block corresponding to the first condition that is true.
Syntax
if (condition1) {
// Code to execute when condition1 is true
} else if (condition2) {
// Code to execute when condition2 is true
} else {
// Code to execute when all above conditions are false
}Example
let score: number = 85;
if (score >= 90) {
console.log("Grade: A");
} else if (score >= 80) {
console.log("Grade: B");
} else if (score >= 70) {
console.log("Grade: C");
} else {
console.log("Grade: F");
}4. switch Statement
The switch statement is used to execute one of multiple code blocks based on the value of an expression. It's typically used as an alternative to if...else if...else statements, especially when all conditions depend on the value of the same variable.
Syntax
switch (expression) {
case value1:
// Code to execute when expression result equals value1
break;
case value2:
// Code to execute when expression result equals value2
break;
// ...can have any number of cases
default:
// Code to execute if expression result doesn't match any case
}- The
breakkeyword is required. It terminates the execution of theswitchstatement. Ifbreakis omitted, code will continue executing the nextcase, which is called "fall-through." - The
defaultclause is optional and used to handle all other cases.
Example
let day: number = new Date().getDay(); // Get current day of week (0-6)
let dayName: string;
switch (day) {
case 0:
dayName = "Sunday";
break;
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
dayName = "Saturday";
break;
default:
dayName = "Invalid day";
break;
}
console.log(`Today is ${dayName}.`);