TypeScript If-Else

In programming, we often need to make decisions. For example, think about a voting application where users can vote only if they are 18 years or older. How do you ensure the application behaves differently for users under 18? This is where conditional statements like if-else come in.

In TypeScript, if-else statements help you control the flow of your program by executing different blocks of code based on conditions.

TypeScript If Statement

Why Do We Need an if Statement?

Imagine you're building a system where a user should receive a message only if they meet a specific condition. For instance, if the temperature exceeds 30°C, you want to display "It's hot today." To achieve this, you need a way to execute code only when a condition is true. The if statement solves this problem.

Syntax:

tsx
1
2
3
if (condition) {
  // Code to execute if the condition is true
}

Example and Explanation:

  • Scenario: You’re building an app to check if a number is positive.
  • Code:
tsx
1
2
3
4
5
let number = 10;

if (number > 0) {
  console.log("The number is positive.");
}
  • Explanation:
    The condition number > 0 checks if the number is greater than zero. If true, the message "The number is positive" is displayed. If false, nothing happens because there’s no alternative condition or block.

TypeScript If-Else Statement

Why Do We Need an if-else Statement?

What if we want to handle two possible outcomes? For example, if a user is old enough, show "Access granted." Otherwise, show "Access denied." The if-else statement lets us handle both scenarios.

Syntax:

tsx
1
2
3
4
5
if (condition) {
  // Code to execute if the condition is true
} else {
  // Code to execute if the condition is false
}

Example and Explanation:

  • Scenario: Checking voting eligibility.
  • Code:
tsx
1
2
3
4
5
6
7
let age = 16;

if (age >= 18) {
  console.log("You are eligible to vote.");
} else {
  console.log("You are not eligible to vote.");
}
  • Explanation:
    • If age >= 18, the if block executes, printing "You are eligible to vote."
    • If the condition is false, the else block executes, printing "You are not eligible to vote."

Ternary Operator ?:

Why Do We Need the Ternary Operator?

Sometimes, you want to write simple if-else logic in fewer lines of code. For example, displaying a status message based on a condition. The ternary operator is a concise alternative to the if-else statement.

Syntax:

tsx
1
condition ? expressionIfTrue : expressionIfFalse;

Example and Explanation:

  • Scenario: Assigning a message based on user role.
  • Code:
tsx
1
2
3
let role = "admin";
let message = role === "admin" ? "Welcome, Admin!" : "Welcome, User!";
console.log(message);
  • Explanation:
    • The condition role === "admin" checks if the user is an admin.
    • If true, "Welcome, Admin!" is assigned to message.
    • If false, "Welcome, User!" is assigned.

TypeScript If-Else If-Else Statement

Why Do We Need an If-Else If-Else Statement?

In some cases, we need to test multiple conditions. For example, assigning a grade based on a student’s score requires checking several ranges. The if-else if-else statement lets us handle such scenarios.

Syntax:

tsx
1
2
3
4
5
6
7
if (condition1) {
  // Code to execute if condition1 is true
} else if (condition2) {
  // Code to execute if condition2 is true
} else {
  // Code to execute if none of the above conditions are true
}

Example and Explanation:

  • Scenario: Grading system based on score.
  • Code:
tsx
1
2
3
4
5
6
7
8
9
10
11
let score = 75;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 75) {
  console.log("Grade: B");
} else if (score >= 50) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}
  • Explanation:
    • The conditions are checked in order. If score >= 90 is true, "Grade: A" is displayed.
    • If the first condition is false, the next condition (score >= 75) is checked, and so on.
    • If none of the conditions are true, the else block executes, assigning a failing grade.

Best Practices for Using If-Else Statements

While if-else statements are powerful, improper usage can lead to hard-to-read code, errors, and performance issues. Following best practices ensures your code remains clean, efficient, and easy to maintain.

  1. Keep Conditions Simple: Break complex conditions into smaller, reusable checks for better readability.
  2. Use Ternary Operator for Simplicity: Use the ternary operator only for simple conditions; avoid using it for complex logic.
  3. Minimize Nested Ifs: Deeply nested if statements can make code difficult to follow. Use functions or switch statements when possible.
  4. Always Cover All Cases: Ensure your conditions handle all possible scenarios to avoid unexpected behavior.
  5. Comment Complex Logic: Add comments to explain why a specific condition is being checked, especially if it’s not obvious.

Frequently Asked Questions