Boolean values can be tranformed and combined via three logical operators:
!
(! true)
false
(! false)
true
sunny
let hot = true; let sunny = true; if( ! sunny ) { alert("bring an umbrella"); }
&&
hot
// assume you have already assigned boolean values to sunny and hot if( sunny && hot ) { alert("wear a hat"); }
||
cold
windy
// assume you already have assigned boolean values to cold and windy if( cold || windy ) { alert("wear a coat!"); }
The meaning of the three logical operators is summarized by the following tables, where inputs are shown in blue like this and outputs are shown in red like this:
Here are some examples of these operators in action. Type a numeric value into the box and click the Evaluate all! button to see the outcome.
Evaluate all!
x
One way to think about these conditionals on numbers is by using the number line, where && means intersection. This is because both conditions have to be true, which is when the regions overlap. For example, consider modeling the expression:
(X >= 5) && (X <= 30)
b
a
c
(a <= b) && (b <= c)
a <= b <= c
7 < 3 < 10 // You might think this expression is false, but it's true. Why? => (7 < 3) < 10 // Relational operator associates to the left => false < 10 // (7 < 3) is false => 0 < 10 // In a numerical context, false is treated as 0, true is treated as 1 => true // (0 < 10) is true!
! true && false is parsed as (! true) && false (which evaluates to false) and not !(true && false) (which evaluates to true)
! true && false
(! true) && false
!(true && false)
Although && and || have a lower precedence than comparison operators, ! has a higher precedence. So ! 2 < -1 evaluates as (! 2) < -1 (whose value is false) and not ! (2 < -1) (whose value is true).
! 2 < -1
(! 2) < -1
! (2 < -1)
Moral: Use explicit parentheses if you have any questions about operator precedence!
Suppose that CS110 lectures are held between 8:30am and 12:20pm. Suppose that hour denotes the hour in military time (in the range 0 - 23) and min denotes the minute (in the range 0 - 59). Our goal is to write a single boolean expression involving hour and min that displays an alert box with true for times during CS110 lectures and false for other times.
hour
min
let hour = parseInt(prompt("Enter the hour (0 - 23)")); let min = parseInt(prompt("Enter the minute (0 - 59)")); alert ((hour >= 8 && min >= 30) && (hour <= 12 && min <= 20));
alert
let hour = parseFloat(prompt("Enter the hour (0 - 23)")); let min = parseFloat(prompt("Enter the minute (0 - 59)")); let startMinutes = 8*60 + 30; let inputMinutes = hour*60 + min; let stopMinutes = 12*60 + 20; alert ( ... flesh out this boolean expression ... );
if
In its simplest form, an if statement can decide whether or not to execute a sequence of statements. For example, in one of our first examples of an if statement, repeated here, the code will either display a message on the condition that the name is "Grover", or otherwise it will do nothing at all.
"Grover"
if (first_name == "Grover") { alert("Hello Grover, great to see you!"); }
Using an else case, an if statement can decide between two alternative sections of code, as in the example where a different message is displayed for "Grover" and any other name:
else
if (first_name == "Grover") { alert("Hello Grover, great to see you!"); } else { alert("Who the heck is " + first_name + "?"); }
There are situations, however, in which more than two alternatives must be considered. For example, suppose you were to write code for assigning letter grades in a class based on the student's final class average.
if (grade >= 90) { letterGrade = "A"; } else if (grade >= 80) { letterGrade = "B"; } else if (grade >= 70) { letterGrade = "C"; } else if (grade >= 60) { letterGrade = "D"; } else { letterGrade = "F"; }
We call this a cascading if statement. The term cascading refers to the way that control cascades down the statement like water down a multi-tiered waterfall. The topmost test is evaluated first, in this case (grade >= 90). If this test succeeds, the corresponding statements are executed and the whole statement is done. If not, control cascades down to the next if test, in this case (grade >= 80). In general, control cascades down the statement from one test to another until one succeeds or the end of the statement is reached, possibly with a final else.
(grade >= 90)
(grade >= 80)
Augment your solution to Exercise 1 (from Part 1) so that there are three possible messages displayed, identifying whether the number is positive, negative, or zero.
let num = parseFloat(prompt("Enter any num")); if (num > 0) { alert("the number is positive"); }
This exercise shows how to generate different pronouns in a madlib based on the gender of the subject.
In the execution box below insert the statement that will use “his” if the person identifies as male and “her” if the person identifies as female, and “their” for anything else.
let name = prompt("What is the person's name?"); let gender = prompt("What is their gender (male/female)?"); let poss_pronoun; alert(name + " was driving " + poss_pronoun + " car when suddenly...");
The braces about the then and else branches of an if statement allow any amount of JavaScript code to be under the control of the conditional — even other if statements. This has exactly the effect you would expect: the code comprised by the inner if statement is conditional on both statements. Let's outline an example, where we categorize something by whether it is positive or not and whether it's even or not. That gives us four possibilities:
if( even ) { ... if( positive ) { // 1. positive even } else { // 2. non-positive even } ... } else { ... if( positive ) { // 3. positive odd } else { // 4. non-positive odd } ... }
Of course, the inner blocks of code don't have to consist solely of the inner if statements. As indicated by the ellipses in the outline above, the inner blocks can have additional code precede or follow the inner if statements. Indeed, that elided code could include other conditionals!
This exercise shows how to assign the correct honorific based upon a person's gender and age. Females under the age of 18 are referred to as Miss, while those 18 and over are referred to as Ms. Similarly, males under the age of 18 are called Mister, while those 18 and over are called Mr.
In the execution box below insert the statements that will assign the correct honorific.
let age = prompt("What is the person's age?"); let gender = prompt("What is the person's gender (male/female)?"); let honorific; alert(" The person shall be called "+honorific);
rock
paper
scissors
p1
p2
"rock"
"paper"
"scissors"
players tie
player 1 wins
player 2 wins
let p1 = prompt("Player 1: enter one of rock,paper,scissors","rock"); let p2 = prompt("Player 2: enter one of rock,paper,scissors","rock"); // flesh out the rest of the program ...