Mastering Conditional Statements in TypeScript
Introduction and Topic Overview
Welcome to our TypeScript undertaking. Today, we are examining the concept of conditional statements. Much like life, TypeScript's conditional statements guide the program based on various conditions.
In today's lesson, we'll cover:
- The basic
ifstatement — the pathway for making single-pathway decisions. elseandelse ifstatements — options for making multiple decision paths.- Compound conditionals — workarounds for handling complex decisions involving multiple conditions.
- The Ternary Operator — a shorthand method for making quick, straightforward decisions.
Understanding Conditional Statements - The Basic If Statement
Our exploration starts with the basic if statement, which validates a particular condition and performs an action if the condition is fulfilled. To illustrate, imagine deciding whether a watermelon is ready to eat, here's what the if statement would look like :
In the above code, the condition watermelon === 'ready' is evaluated. If it is true, the action inside the { ... } block is executed, which is console.log("The watermelon is ready. It's time to enjoy."); in this case.
Diving Deeper - Exploring Else and Else If Statements
What would happen if the watermelon is not ready? Here, we use the else statement, which specifies a different course to follow when the if condition is false.
To evaluate multiple conditions, we place an else if statement after the if statement and before the else statement. Here's an example of decision-making based on temperature:
The code above prints "Temperature is below freezing; stay indoors.".
Raising The Decision Making Game - Compound Conditionals
