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 if statement — the pathway for making single-pathway decisions.
  • else and else 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.
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 :

let watermelon: string = 'ready';

if (watermelon === 'ready') {
    // If our watermelon is ready, the message is printed.
    console.log("The watermelon is ready. It's time to enjoy.");
}
/*
Prints: "The watermelon is ready. It's time to enjoy."
*/

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:

let temperature: number = -1;

if (temperature > 0) {
    console.log("Temperature is above freezing; let's go outside.");
} 
else if (temperature === 0) {
    console.log("Temperature is at the freezing point; better stay warm.");
}
else {
    console.log("Temperature is below freezing; stay indoors.");
}
/*
Prints:
"Temperature is below freezing; stay indoors."
*/

The code above prints "Temperature is below freezing; stay indoors.".

Raising The Decision Making Game - Compound Conditionals
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal