Comp 110 Conditional Operators

Conditional Operators

Booleans are either true or false, but did you know that we can have expressions which evaluate to true or false, and are thereby booleans?? Super cool right?

 We can do this with conditional operators. There are several operators that help us compare data, we'll discuss these below.

Equality Operators

  • ===
    • This is the equal to operator. It has THREE equals symbols in a row.
    • It should only be used with simple data types (number, string, boolean) and not with objects or arrays.
  • !==
    • This is the not equal to operator. It uses the ! symbol to mean "NOT." 
    • It is the ! symbol followed by TWO equals symbols.

Relational Operators

  • >
    • Greater than
  • >=
    • Greater than or equal to
    • At least
  • <
    • Less than
  • <=
    • Less than or equal to
    • At most

Logical Operators and Negation

Logical operators and negation are useful for creating compound logical statements.

  • &&
    • AND operator
    • double ampersand
    • Using the AND operator with boolean expressions results in true only if both expressions are true.
  • ||
    • OR operator
    • double vertical bar
    • Using the OR operator with boolean expressions results in true if either expression is true or if both expressions are true.
  • !
    • NOT operator
    • This operator gives us the flipped meaning of a boolean - so if something normally evaluates to true, prefacing it with the ! operator will result in a false value, and if something is normally false, using the ! operator will result in true.

Examples

let x: number = 7;
let y: number = 3;

let a: boolean = x > y; 
print(a); //prints true
print(!a); //prints false - the inverse of a
let b: boolean = y >= x; 
print(b); //prints false
let c: boolean = a && b; 
print(c); //prints false - remember for && both a and b must return true
let d: boolean = a || b;
print(d); //prints true - for || only one must be true for the statement to return true

Useful Tables