Comp 110 Logical Flow with Booleans

Logical Flow with Booleans

If

Using booleans or boolean expressions, which either 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.

Operators

<         (less than)

>         (greater than)

<=        (less than or equal to)

>=        (greater than or equal to)

===       (equal to)

&&        (and)

||         (or)

The majority of the operators work exactly as you'd expect, with something like 5 < 3 evaluating to true and 2 === 7 evaluating to false.

And (&&)

If both boolean expressions are true, then the resulting expression evaluates to true. If either boolean or just one is false, the expression will evaluate to false.

Or (||)

If either expression is true, then the resulting expression evaluates to true. If both booleans are false, the expression will evaluate to false.