Mastering Conditional Logic with TypeScript if...else Statements

Learn how to control the flow of your TypeScript programs using if...else statements. Understand the syntax, conditions, and best practices for making decisions based on different scenarios.



TypeScript Conditional Statements

TypeScript provides several conditional statements to control the flow of your program based on different conditions.

if Statement

Executes a block of code if a specified condition is true.

TypeScript Code

let age = 18;
if (age >= 18) {
  console.log("You are an adult.");
}

if...else Statement

Executes one block of code if a condition is true, and another block if the condition is false.

TypeScript Code

let age = 16;
if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

else if Statement

Checks multiple conditions sequentially.

TypeScript Code

let grade = 90;
if (grade >= 90) {
  console.log("Excellent");
} else if (grade >= 80) {
  console.log("Good");
} else {
  console.log("Needs Improvement");
}

Ternary Operator

A shorthand way to write an if...else statement.

TypeScript Code

let age = 18;
let isAdult = age >= 18 ? "You are an adult" : "You are a minor";
console.log(isAdult);

Key Points

  • Conditions in if statements must evaluate to boolean values.
  • Indentation improves code readability.
  • Nested if statements can be used for complex logic, but can become harder to maintain.
  • The ternary operator is useful for simple conditional expressions.

Best Practices

  • Use clear and meaningful variable names.
  • Add comments to explain complex logic.
  • Consider using switch statements for multiple comparisons with the same value.

By understanding these conditional statements, you can effectively control the flow of your TypeScript programs based on different conditions.