Comp 101 Operators and Logic with Booleans

Logical Flow with Booleans


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.


Adding the "else" keyword to an if-statement allows the programmer to provide an additional code block providing alternative instructions 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) executes only when the conditional is false. Therefore, only one of the code blocks executes.


<         (less than)

>         (greater than)

<=        (less than or equal to)

>=        (greater than or equal to)

===       (equal to)

!==        (not 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.

Not (!)

The not operator negates the value of a variable or boolean statement. Meaning if the boolean would otherwise evaluate to true adding a not operator will make the expression evaluate to false and vice versa.

The table below can be helpful for understanding when different combinations of ands/ors/nots will evaluate to true or false!