Comp 110 If-Else and Else-If Statements

If

Using booleans or boolean expressions, which evaluate to true or false, we can create complex logical programs. If-then statements involve the keyword if, parenthesis (), curly braces {} and some code to execute!

if (<conditional statement>) {      // code to execute
}

The conditional statement acts as a gate to the code contained within its curly braces, only allowing the program to access and execute the code in the braces if the expression evaluates to true.

The code above and below the if-block are completely independent from the conditional, however, and will execute regardless of the conditional statement's truth value.

Else

Adding the else keyword to an if-statement allows the programmer to provide an additional code block in the case that the conditional statement evaluates to false.

if (<conditional statement>) {      // code to execute
} else {      // code that executes when conditional statement false
}

The code within the else block (surrounded by the curly braces after the else keyword and after the comment) executes only when the conditional is false. Therefore, only one of the code blocks (that in the if-block and that in the else-block) executes.

There are tons of conditional operators that can be used within if-else blocks! Check out the Conditional Operators page for details!

What about else-if blocks?

When using if-statements, sometimes it can be much easier to specify an if-conditional as a part of an else statement.

Lets check out an example!

if (myAge < 18) {
      print("aw yous a baby");
}
if (myAge < 21) {
      print("almost there!");
}
if (myAge === 21) {
      print("get littt");
if (myAge > 21) {
       print("now ur old");
}

If myAge is 18, what will happen? 

"aw yous a baby" will print...but what else?

since 18 < 21, "almost there!" will also print - but that isn't ideal...

So how can we arrange these conditionals to check for MULTIPLE cases, but not allow more than one case to execute?

Use an else-if!

if (myAge < 18) {
      print("aw yous a baby");
} else if (myAge < 21) {
      print("almost there!");
} else if (myAge === 21) {
      print("get littt");
} else {
       print("now ur old");
}

Now when myAge is 18, ONLY "aw yous a baby" will print since it satisfies the first condition. Once a condition is satisfied, we exit the conditional completely, and no other condition will be checked! 

Using else-if statements help us direct the logical flow of a program by increasing our control over which boolean combinations lead to which output. We can make more complex code that does more with fewer lines!