Bootcamp Notes – Day 14 (Tues) – Making Decisions with JavaScript

 

Making Decisions

Conditional Statements: IF

Conditional statements represent a fork or multiple Forks in a path. When a program encounters a conditional statement, it will evaluate a given condition then decide what code to run based on that evaluation. The simplest form of a conditional statement is an if statement.
An if statement evaluates a condition and executes a block of code, if the condition evaluates as true. Take note of the syntax of an if statement. First in the word if, this is immediately followed by a condition to be evaluated inside a set of parentheses, then a begin curly brace, which signals the beginning of code block, which is a block of one or more statements to be executed, when the if condition evaluates as true or truthy. At the end, a closing curly brace on its own line. All of this together makes makes up a single if statement. You do not need to use a terminating semicolon after a curly brace that ends a code block. The triple equals operator compares the value stored inside this variable named password, and the string super-secret password, and returns a boolean value of true if they match and false if they don’t.

 

Conditional Statements: IF..ELSE
 
If statements can also have what’s called an else block, which comes right after the end of the if block like this:

 

So after the closing curly brace for the if block, you add the keyword else, then another code block between curly braces, this is where you put statements that you want to run only when the if condition is false. The else block will run only when the if condition is false.

Conditional Statements: IF… ELSE IF … ELSE

Test more conditions in the same statement with else if:

 

If you want to test more conditions in the same statement, you optionally add else–if blocks between the if announced blocks. This if statement above for example, would check the value of the variable color then assign a value to the variable hex color code. It should make sense when you read it, fairly naturally, if the color equals red, then the hex code is this, else if the color equals black then, the hex color code is this, and if the color didn’t equal red or black then the hex color is no. Each if statement can only have one if block and one else block, but you can add as many else if block in between them as you wish.

TRUTHY & FALSY

If statements check for whether a condition is truthy or falsy. These are slightly different concepts from the BOOLEAN values of true and false. True and false are boolean values, and are represented by the words true and false. Values can be converted to other data types – a number to a string, a string to a Boolean, a Boolean to a number, etc. When a value, that is not of the boolean data type, would be boolean true if it was converted to boolean, then we consider that value to be truthy. If it’s not boolean true, but would be if converted if  a non boolean value would be false if converted to a boolean, then it is falsy.
How to determine whether a value is truthy or falsy.
These values are falsy (would be false if converted to Boolean):
  1. false
  2. undefined 
  3. null
  4. 0
  5. -0 
  6. NaN (not a number)
  7. empty string ” ” or ‘  ‘
Every other value not on this list is truthy. Example: 3, -3, ‘any non-empty string’
Now why would truthy or falsy be useful?
Some conditions do have a value of Boolean true/false for example:
(paassword === ‘SuperSecretPassword’)
or Sometimes you may only want to check that a value hold some truthy value, that it doesn’t contain null/undefined/any other falsy values for example:
if (password) {
.. code to check if password is correct..
} else {
    prompt(‘You must enter a password: ‘);
}
Knowing that the if condition operates on truthy or falsy will help you to understand and write code that doesn’t depend on boolean true or false conditions alone.

Overview: JavaScript Operators

OPERATORS & OPERANDS
Operators are characters that operate on one or more values. The operation can take many forms – an assignment, a comparison, a mathematical operation, etc
Assignment operator: x = 5;
The values involved in an operation are operands in this case, x is the left operand, 5 is the right operand.
  • Operator with 1 left and 1 right operand (most common): binary operator
  • Operator with 1 operand: unary operator
  • Operator with 3 operands (only one): ternary operator
 
Using Multiple Operators
More than one operator can be used in a single statement, for example: x = y +3.  (This example uses both the assignment operator and the addition operator
You can have multiple operators in the same operand, for example: x = y + 3 * 5
There is an established order of operator precedence – for example, as in math, multiplication operations are done before addition operations. Use parentheses to make clear your intended order of operations. For example x = y + (3 * 5) is not the same as x = (y+3) * 5
 

Operator Categories

  1. Comparison Operators
  2. Logical Operators
  3. Assignment Operators
  4. Arithmetic Operators
  5. String Operators
  6. and more!

COMPARISON OPERATORS

All comparison operators are binary operators. They compare two values and return Boolean true or false. Two types: equality and relational

 

===  Strict equality operator compares operands’ value and type
==    Loose equality operator performs type coercion when types do not match
(type coercion: implicit type conversion, type converted without explicit request)
Examples:

!==  Strict inequality operator compares type and value

!=    Loose inequality operator performs type coercion before comparing value.

 

Relational Operators

>    greater than
<    less than
>=  greater than or equal to
<=  less than or equal
With number operands, relational operators work as you would expect:
5  > 10 is false
x = 23;  is true
x <= 50 is true

String operands are compared in lexicographical order, where a is lower/lesser & z is higher/greater; if characters match, compare next character for example:

‘a’ <= ‘z’  is true
‘peony’ > ‘oboe’  is true
‘aardvark’ > ‘anteater’  is false
‘eefffgg’ >= ‘eefffgh’ is false

Logical Operators

Three logical operators in JavaScript: &&   ||   !
&& and || are binary:  x && y    x || y
! is unary:  !x
Logical AND: &&
Suppose, a theater wants to have a general admission ticket price of $20 for ages over 12 and under 65, and a discounted ticket price of $10 for ages 12 and under, or 65 and over. — How would you write this logic using an if statement?
if ((age > 12) && (age < 65)) {
    ticketPrice = 20;
} else {
    ticketPrice = 10;
}
 

Expression

Return  Value

true && true

true

true && false

false

false && true

false

false && false

false

  • && tests if the left operand is truthy or falsy
  • If falsy, it will return the left operand’s value
  • If truthy, it will return the right operand’s value
To say another way, && returns the last truthy value if both operands are truthy; if either operand is falsy, then && returns the first falsy value. Look at the example below:

Now look at it applied to the console in Chrome Browser! You can see it matches the results from above. Cool huh?

 

 
Logical OR: ||
 
 
Now suppose, your friends are forming a band and you want to join. They tell you that you can join if you play an instrument, or if you can sing. You don’t have to both plat an instrument and be able to sing-fulfilling either condition make you eligible to join the band. This is the basic idea of || operator.

Expression

Return  Value

true || true

true

true || false

true

false || true

true

false || false

false

|| tests if the left operand is truthy or falsy

If truthy, it will return the left operand’s value

If falsy, it will return the right operand’s value

|| returns the first truthy value; if neither operand is truthy, then it will return the last falsy value.
|| this called the pipe character, which is just above the return key on your keyboard.
Comparison Chart of && and ||

 

Expression

Return  Value

Expression

Return  Value

true && true

true

true || true

true

true && false

false

true || false

true

false && true

false

false || true

true

false && false

false

false || false

false

 

LOGICAL NOT: !

! is a unary operator (meaning it has one operand) and it is placed just before the operand, no space
Always returns true or false: returns false when its operand’s value is truthy, true when its operand’s value is falsy.
! type coerces its operand to a Boolean value then negates that value.
Use parentheses around the operand to ensure ! operates on the entire operand and not the first value in it.

 

Expression

Return  Value

!true

false

!false

true

!’cat’

false

!(3 > 2)

false

!’bootcamp’ === true

false

!(’bootcamp’ === true)

true

 

The Double Not Operator: !!
|| also called Bang Bang. Not a new operator, but a clever use of the ! operator as a shorthand for Boolean conversion.
Built-in JavaScript function Boolean() can be used to convert values to Boolean date type:  Boolean(123) true
Or, use first ! to coerce a value (or expression) to Boolean & negate it:   !123 false
Then use second ! to reverse the negation:   !!123 true
Now we take everything we have learned so far and do this Exercise: Functions and Conditions – Purchase tickets at a theater. Look at the final code for it here at codepen!
Conditional Statements: Switch
 

Below in the example is the basic syntax of a switch statement. The switch statement evaluates a given expression then executes code based on different values for that expression. It contains four key words to get to know: switch, case, break and default. Each case represents a different value that the expression being evaluated could be the switch statement runs all statements beneath the case that matches the expression until a break statement is hit.

Here is a switch example:

switch(size) {
    case ‘small’:
        alert(‘This chair is to small!’);
        break;
    case ‘medium’:
        alert(‘This chair is just right!’);
        break;
     case ‘large’:
        alert(‘This chair is to big!’);
        break;
     default:
        alert(‘This chair is an unknown size!’);
}
The default case should always be at the bottom. The break statement is used at the end of a case in order to break out of the switch statement. If you don’t include the break statement, then the program
will go into the next case, even if it doesn’t match the expression and run its code. And if that case still doesn’t have a break statement they will continue on to the next case and execute its code until it gets to a break statement. You see, when the switch statement evaluates the expression in this case size and looks for a matching case. It’s looking for a starting point. It will start there and then run any statement after that case even the ones that preload other cases until it hits a break.
Additional Resources:

 

You May Also Like