WEEK: 7
Active: February 21st - February 27th
Work Due: February 28th @ 9:00AM

Logical Operators

Boolean Algebra is used to describe “logical relations” in the same way that Algebra is used to describe “numeric relations”. Boolean algebra takes two or more conditional statements and compares their truth value against each other.

Logical AND

The Logical And Operator compares two Boolean expressions.

  • If both Boolean values/statements evaluate to true than the operator returns true.
  • If either Boolean value/statement evaluates to false than the operator returns false.

The Logical And Operator is expressed with 2 ampersand keys placed together (the ‘and’ character on the ‘7’ key).

&& // ← Logical And Operator

Let’s look at all possible expressions and their results using Boolean values.

true && true // ⇒ returns true
true && false // ⇒ returns false
false && true // ⇒ returns false
false && false // ⇒ returns false

As you can see, both of the operators Boolean values must be true for the statement to return true.

Logical OR

There is also a Logical Or Operator. This operator returns true if *either of the Boolean values being evaluated are true.

The Logical Or Operator is specified using two pipe characters, This character is typically found on as the “shift character” on the backslash, which is the key above “return”.

|| // ← Logical Or Operator

Following the above example, let’s look at all the possible statement combinations and the result.

true || true // ⇒ returns true
true || false // ⇒ returns true
false || true // ⇒ returns true
false || false // ⇒ returns false

As you can see, only one of the Boolean values needs to be true for the statement to return true.


Previous section:
Next section: