The "if" statement in TypeScript is a fundamental conditional statement that allows you to execute a block of code if a specified condition is true.
Example:
const age = 18;
if (age >= 18) {
console.log("You are eligible to vote.");
}
If..Else Statement:
The "if..else" statement in TypeScript extends the basic "if" statement by providing an alternative block of code to execute if the condition is false.
Example:
const isRaining = true;
if (isRaining) {
console.log("Don't forget your umbrella!");
} else {
console.log("No need for an umbrella today.");
}
If-Else-If Statement (or ladder):
The "if-else-if" statement in TypeScript allows you to test multiple conditions in sequence and execute different blocks of code based on the first true condition encountered.
Example:
const score = 75;
if (score >= 90) {
console.log("You got an A.");
} else if (score >= 80) {
console.log("You got a B.");
} else if (score >= 70) {
console.log("You got a C.");
} else {
console.log("You need to improve your score.");
}
Switch Statement:
The "switch" statement in TypeScript is used to perform different actions based on different conditions. It provides a way to simplify multiple "if-else" conditions when you have a value to compare against.
Example:
const dayOfWeek = "Monday";
switch (dayOfWeek) {
case "Monday":
console.log("It's the start of the workweek.");
break;
case "Friday":
console.log("It's almost the weekend!");
break;
default:
console.log("It's just another day.");
}