We are going to introduce two new concepts. Let's start with the else if
statement. Since the if-else
statement only supports two blocks, you might have thought about how you were going to approach issues will multiple possible outcomes. This is where the else if
statements comes into play. The else if
statement can be used as many times as you like to increase the possible outcomes.
The other concept is nesting if
statements. The if
and if-else
statements can be nested, meaning they can be used inside another if
or else
statement. Every else
statement corresponds to its closest preceding if
statement. Always use the curly braces to avoid ambiguity and to make your code more readable. Avoid using more than three levels of nested if
statements, and put the case you normally expect before the more rare cases.
The sample code above is a simple program that prints out the number on the dice depending on the value of the variable. As you can see, there are many if
statements and else-if
statements so that all the possibilities are considered. Nested if
statements are used when the dice number is divisible by two. The final console.log()
statement under the else
statement will print if and only if the value of diceNumber
is not between 1 and 6. Try playing around with the value of diceNumber
to print different messages.
Edit Me on GitHub!