TypeScript - Decision Making

Hello, aspiring programmers! Today, we're going to dive into one of the most crucial concepts in programming: decision making. As your friendly neighborhood computer teacher, I'm excited to guide you through this journey in TypeScript. Don't worry if you've never written a line of code before – we'll start from the very beginning and work our way up together.

TypeScript - Decision Making

What is Decision Making?

Before we jump into the code, let's talk about what decision making really means in programming. Imagine you're playing a video game. The game constantly makes decisions based on your actions: if you press the jump button, your character jumps; if you run into an enemy, you lose a life. This is decision making in action!

In programming, decision making allows our code to make choices based on certain conditions. It's like giving your program a brain to think and act accordingly.

The if Statement

The most basic form of decision making in TypeScript (and many other programming languages) is the if statement. Let's look at a simple example:

let playerScore = 75;

if (playerScore > 50) {
    console.log("You passed the level!");
}

In this code, we're checking if the player's score is greater than 50. If it is, we print a congratulatory message. Let's break it down:

  1. We declare a variable playerScore and set it to 75.
  2. The if keyword starts our decision-making process.
  3. Inside the parentheses, we have our condition: playerScore > 50.
  4. If this condition is true, the code inside the curly braces {} will run.

Run this code, and you'll see "You passed the level!" printed out. Try changing the playerScore to 40 and see what happens!

The if-else Statement

But what if we want to do something when the condition isn't true? That's where the else statement comes in handy:

let playerLives = 0;

if (playerLives > 0) {
    console.log("Game on! You're still alive.");
} else {
    console.log("Game over! Better luck next time.");
}

Here, we're checking if the player has any lives left. If they do, the game continues. If not, it's game over. This is a great example of how games use decision making to control the flow of the game.

The else-if Statement

Sometimes, we need to check multiple conditions. That's where else if comes in:

let grade = 85;

if (grade >= 90) {
    console.log("A - Excellent!");
} else if (grade >= 80) {
    console.log("B - Good job!");
} else if (grade >= 70) {
    console.log("C - Not bad, keep improving!");
} else {
    console.log("You need to study more!");
}

This code checks a student's grade and provides different feedback based on the score. It starts with the highest grade and works its way down. As soon as a condition is true, that block of code runs, and the rest are skipped.

The switch Statement

When you have many conditions to check, especially if you're comparing a single variable against multiple values, the switch statement can be cleaner and more efficient:

let dayNumber = 3;
let day: string;

switch (dayNumber) {
    case 0:
        day = "Sunday";
        break;
    case 1:
        day = "Monday";
        break;
    case 2:
        day = "Tuesday";
        break;
    case 3:
        day = "Wednesday";
        break;
    case 4:
        day = "Thursday";
        break;
    case 5:
        day = "Friday";
        break;
    case 6:
        day = "Saturday";
        break;
    default:
        day = "Invalid day";
}

console.log(`The day is ${day}`);

This switch statement checks the value of dayNumber and assigns the corresponding day name to the day variable. The break statement is crucial here – it tells the code to stop checking other cases once a match is found.

Conditional (Ternary) Operator

For simple if-else decisions, TypeScript offers a shorthand called the ternary operator. It's a bit like asking a yes/no question:

let age = 20;
let canVote = age >= 18 ? "Yes" : "No";

console.log(`Can this person vote? ${canVote}`);

This code checks if age is 18 or older. If it is, canVote is set to "Yes"; otherwise, it's "No". It's a concise way to write simple if-else statements.

Nested Decision Making

Sometimes, you need to make decisions within decisions. This is called nesting:

let isRaining = true;
let hasUmbrella = false;

if (isRaining) {
    if (hasUmbrella) {
        console.log("You can go outside with your umbrella!");
    } else {
        console.log("Better stay inside, you don't have an umbrella.");
    }
} else {
    console.log("Enjoy the nice weather outside!");
}

This code first checks if it's raining. If it is, it then checks if you have an umbrella. Based on these nested conditions, it gives you different advice.

Summary of Decision-Making Methods

Here's a quick reference table of the decision-making methods we've covered:

Method Use Case Syntax
if Single condition if (condition) { ... }
if-else Two possible outcomes if (condition) { ... } else { ... }
else-if Multiple conditions if (condition1) { ... } else if (condition2) { ... } else { ... }
switch Multiple cases for a single variable switch (variable) { case value1: ... break; case value2: ... break; default: ... }
Ternary Simple if-else in one line condition ? valueIfTrue : valueIfFalse

Remember, the key to mastering decision making in programming is practice. Try creating your own scenarios and implementing these different methods. Maybe create a simple text-based game that uses decisions to progress the story!

As we wrap up, I want to share a little programming wisdom: Code is a lot like cooking. You start with basic ingredients (variables), follow a recipe (algorithms), and use different techniques (like decision making) to create something amazing. So don't be afraid to experiment and have fun with it!

Keep coding, stay curious, and happy decision making!

Credits: Image by storyset