Making Decisions with Conditionals: An Overview

Greetings, coding explorer!

Today, we're diving into conditional statements, a key principle in programming. Conditionals, like day-to-day decisions, are dictated by circumstances. For instance, should it rain, you'd opt for an umbrella. Code operates in a similar manner. They control the flow of code, mobilizing actions based on whether conditions are true or false. We'll be exploring this concept today.

The "if" Statement: Initiating Decision-Making

Regard the if statement as the gatekeeper of conditionals. It definitively states, "If this is true, then perform this specific action". It’s comparable to choosing between chocolate and vanilla ice cream. Let’s take a closer look at an example:

let myScore = 100;
let friendScore = 80;
// If our score is higher, we get to brag about it!
if (myScore > friendScore) {
    console.log("Score bragging rights are mine!");
    console.log("Victory is sweet!");
}

console.log("Game over.");

Note that in JavaScript, the conditions we inspect using if statement must always be wrapped in parentheses, like so: if (condition). The if statement applies to all statements within its block formed by braces ({}).

In the above script, since myScore is greater than friendScore, both lines within the block are executed. If myScore was smaller than friendScore, they would not.

Regardless of the condition's verdict, "Game over." is printed because it's situated outside the if block.

The "else" Statement: Expanding Our Options

Often, we're presented with multiple potential outcomes. For such instances, we utilize the else statement, to account for the "otherwise" scenario. Let's see it in action:

let myScore = 60;
let friendScore = 80;
// If our score is higher, we brag. Else, we console ourselves!
if (myScore > friendScore) {
    console.log("I scored higher!");
    console.log("Hurrah!");
} else {
    console.log("My friend scored higher. Well played.");
    console.log("I’ll come back stronger next time.");
}

console.log("Game over.");

In this scenario, if the if statement's condition is met, the program executes only the block within the if statement. However, if the condition is false and thereby the first block is not executed, the program moves to execute the block within the else clause instead.

Again, irrespective of the chosen path, "Game over." is always printed as it resides outside the conditionals’ realm.

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