TypeScript - If...Else Statement: A Beginner's Guide

Hello there, future coding superstar! ? Today, we're going to dive into one of the most fundamental concepts in programming: the if...else statement in TypeScript. Think of it as the decision-maker in your code, like a wise owl that helps your program choose which path to take. Let's embark on this exciting journey together!

TypeScript - If Else Statement

What is an If...Else Statement?

Before we jump into the nitty-gritty, let's understand what an if...else statement is. Imagine you're at an ice cream shop, and you have to decide between chocolate and vanilla. Your thought process might go like this:

"If chocolate is available, I'll have chocolate. Otherwise (else), I'll have vanilla."

That's exactly how an if...else statement works in programming! It allows your code to make decisions based on certain conditions.

Syntax

Now, let's look at how we write an if...else statement in TypeScript. Don't worry if it looks a bit strange at first – we'll break it down step by step!

if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Let's break this down:

  1. if: This keyword starts the statement.
  2. (condition): This is where you put your condition. It's like asking a question.
  3. { }: These curly braces contain the code to run if the condition is true.
  4. else: This keyword introduces the alternative option.
  5. { }: These curly braces contain the code to run if the condition is false.

Flowchart

To visualize how an if...else statement works, let's look at a simple flowchart:

       [Start]
          |
          v
    [Check condition]
      /           \
    (Yes)        (No)
     |             |
     v             v
[Execute true]  [Execute false]
     |             |
     v             v
       [Continue]

This flowchart shows how your program decides which path to take based on whether the condition is true or false.

Examples

Now, let's dive into some real-world examples to see how if...else statements work in action!

Example 1: Ice Cream Decision

Let's code our ice cream decision from earlier:

let chocolateAvailable: boolean = true;

if (chocolateAvailable) {
    console.log("Great! I'll have chocolate ice cream.");
} else {
    console.log("I guess I'll have vanilla ice cream then.");
}

In this example:

  • We declare a variable chocolateAvailable and set it to true.
  • The if statement checks if chocolateAvailable is true.
  • Since it is true, the code inside the first set of curly braces will run.
  • The console will display: "Great! I'll have chocolate ice cream."

Try changing chocolateAvailable to false and see what happens!

Example 2: Greeting Based on Time

Let's create a program that greets you differently based on the time of day:

let currentHour: number = 14; // 2 PM

if (currentHour < 12) {
    console.log("Good morning!");
} else if (currentHour < 18) {
    console.log("Good afternoon!");
} else {
    console.log("Good evening!");
}

Here's what's happening:

  • We set currentHour to 14 (2 PM).
  • The first condition currentHour < 12 is false, so we move to the next condition.
  • currentHour < 18 is true, so "Good afternoon!" is logged to the console.
  • The last else block is skipped.

Example 3: Grade Calculator

Let's create a simple grade calculator:

let score: number = 85;
let grade: string;

if (score >= 90) {
    grade = "A";
} else if (score >= 80) {
    grade = "B";
} else if (score >= 70) {
    grade = "C";
} else if (score >= 60) {
    grade = "D";
} else {
    grade = "F";
}

console.log(`Your grade is: ${grade}`);

In this example:

  • We set a score of 85.
  • We use multiple if...else if statements to check the score against different ranges.
  • Since 85 is greater than or equal to 80, the grade is set to "B".
  • Finally, we log the grade to the console.

Common Methods and Their Usage

Here's a table of common methods and operators you might use with if...else statements:

Method/Operator Description Example
=== Strict equality if (x === 5)
!== Strict inequality if (y !== 10)
> Greater than if (age > 18)
< Less than if (temperature < 0)
>= Greater than or equal to if (score >= 60)
<= Less than or equal to if (quantity <= 0)
&& Logical AND if (x > 0 && x < 10)
|| Logical OR if (day === "Sat" || day === "Sun")
! Logical NOT if (!isLoggedIn)

Conclusion

Congratulations! You've just taken your first steps into the world of conditional programming with TypeScript's if...else statements. Remember, these statements are like the traffic lights of your code, guiding your program down different paths based on the conditions you set.

As you continue your coding journey, you'll find yourself using if...else statements all the time. They're incredibly versatile and powerful. So, keep practicing, and soon you'll be making decisions in your code as easily as choosing between chocolate and vanilla ice cream!

Happy coding, and remember – in programming, as in life, it's all about making the right choices! ??

Credits: Image by storyset