Welcome to our new JavaScript adventure. Today, we're exploring the world of conditional statements. Just as decisions are made in real life, conditional statements in JavaScript guide a program in determining which steps to take under certain conditions.
In this lesson, we're going to explore:
- The basic
ifstatement — the pathway for making single-pathway decisions. elseandelse ifstatements — options for making multi-pathway decisions.- Compound conditionals — an alternative for managing complex decisions involving multiple conditions.
- The Ternary Operator — a shorthand method for making swift, simple decisions.
Our journey begins with the straightforward if statement, which checks a specific condition and takes action if the condition is true. Similar to determining whether an apple is ripe enough to eat, the if statement would appear like this :
Here, the if-condition checks the condition (apple === 'ripe'), and if it is true, it performs the action inside the { ... } block, which is a console.log("The apple is ripe. It's ready to be eaten."); statement here.
So, what if the apple isn't ripe? In this case, we use the else statement, which defines an alternative course of action 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. This process mirrors our daily decision-making based on the weather:
The above code prints "Snowy day, let's enjoy a snowball fight!".
