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
if
statement — the pathway for making single-pathway decisions. else
andelse if
statements — 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.
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.
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."
.
What if we need to consider multiple conditions before making a decision? Compound conditional statements utilize logical operators (and - &&
, or - ||
) to combine conditions. A decision to go cycling based on multiple factors acts as a prime example:
The Ternary Operator ? :
is an ideal pick for quick if-else
decisions. This shorthand expression verifies a condition, executing the code after ?
if true or the code after :
if false.
Great job! Today, we learned about making decisions using TypeScript's conditional statements. We plunged into the basic if
statements, explored else
and else if
branches, compound conditionals, and the shorthand ternary operator.
Next, it’s time for exercises! Fortify your comprehension by applying today's enriching lesson to multiple scenarios. Prepare for an upcoming deep dive into TypeScript types, interfaces, and more. Keep progressing!
