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.
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:
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.
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:
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.
