CPNT 262 Day 6 - Booleans, comparison operators and conditionals

Housekeeping

  • Quick chat about Fat arrow functions
  • No more Node until we start backend on Oct 26

Trophy of the Day


1. Spoiler demo


2. Equality and Truthiness

Coercion in untyped languages (such as Javascript) produces a concept known as "Truthiness": some values are more equal than others, based on their value type.

Materials

Key Takeaways

  • Use === when testing for equality (it's safer). Use == once you understand truthiness (or you just can't get the job done with ===).

  • Any value can be converted to a Boolean value:

    myBool = Boolean(myVar); // Method 1
    myBool = !!myVar; // Method 2

Activities

  • Why does 3 > 2 > 1 evaluate to false?

3. Conditional code blocks

The if/else statement is used to conditionally run code when an expression is true.

Materials

Key Takeaways

  • An if block only runs if its expression evaluates to true
  • An else if block only runs if its expression evaluates to true AND all if and else if blocks before it have evaluated to false.
  • An else block only runs if all previous if and else if blocks have evaluated to false.
  • The AND logical operator (&&) only evaluates to true if both operands also evaluate to true.
  • The OR logical operator (||) evaluates to true if EITHER of the two operands evaluate to true.
  • The NOT logical operator (!) inverts a true value to false, and vice versa.

Activities


4. Value validation

A common task in untyped languages is confirming the value type that you're working with.

Materials

Activity

  • Using your knowledge of comparison operators and conditional statements, add validation to your Tip Calculator that ensures that:
    1. The entered Bill Total is greater than $0, and
    2. The supplied Service Level is one of the options available in the select menu.

Prep

Booleans and Conditional Statements

Logical operators

Forms