Introduction and Topic Overview

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 if statement — the pathway for making single-pathway decisions.
  • else and else if statements — 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.
Understanding Conditional Statements - The Basic 'If' Statement

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 :

let apple = 'ripe';

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

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.

Entering the Complex Zone - Exploring 'Else' and 'Else If' Statements

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:

let weather = 'snowy';

if (weather === 'sunny') {
    console.log("It's sunny, let's go for a walk.");
} 
else if (weather === 'rainy') {
    console.log("Rainy day, we'd better stay at home.");
} 
else if (weather === 'snowy') {
    console.log("Snowy day, let's enjoy a snowball fight!");
}
else {
    console.log("The weather's unclear. Let's stay home and read a good book.");
}
/*
Prints:
"Snowy day, let's enjoy a snowball fight!"
*/

The above code prints "Snowy day, let's enjoy a snowball fight!".

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