# Booleans and Conditionals Part 2

## Logical Operators

Boolean values can be tranformed and combined via three logical operators:

1. `!` (pronounced "not") is a unary (one-argument) operator that negates a boolean value: `(! true)` is `false` and `(! false)` is `true`. If `sunny` is a variable that contains a boolean value, you might use the not operator like this:
```var hot = true;
var sunny = true;
if( ! sunny ) {
}
```
2. `&&` (pronounced "and") is an infix binary (two-argument) operator that returns `true` if and only if both arguments are `true`; otherwise it returns `false`. If `sunny` and `hot` are variables that contain boolean values, you might use the and operator like this:
```// assume you have already assigned values to sunny and hot
if( sunny && hot ) {
}
```
3. `||` (pronounced "or") is an infix binary (two-argument) operator that returns `true` if and only if at least one of its arguments is `true`; otherwise it returns `false`. If `cold` and `windy` are variables that contain boolean values, you might use the or operator like this:
```// assume you already have assigned values to cold and windy
if( cold || windy ) {
}
```

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:

Negation (not) Conjunction (and) Disjunction (or)
 true false ! false true
 && true false true true false false false false
 || true false true true true false true false

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.

Expression Value Notes
x
(5 <= x) && (x <= 20) `x` is between 5 and 20 (inclusive)
(x < 10) || (x > 25) `x` is not between 10 and 25 (inclusive)
!((15 <= x) && (x <= 30)) `x` is not between 15 and 30 (inclusive)

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)` #### Gotchas

• To test whether `b` is between `a` and `c` (inclusive), in JavaScript you write ```(a <= b) && (b <= c)```. Unlike in mathematics, the JavaScript expression ```a <= b <= c``` does not have the same meaning. Why? Consider the evaluation of the following example:
```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!
```
• `!` has a higher precedence than `&&`, which has a higher precedence than `||`. For example:

`! true && false` is parsed as `(! true) && false` (which evaluates to `false`)
and not `!(true && false)` (which evaluates to `true`)

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`).

Moral: Use explicit parentheses if you have any questions about operator precedence!

#### Exercise 2

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.

1. It seems reasonable to think of this as an and operation: the time is equal to or after 8:30 and before or equal to 12:20. But the following attempt does not work. Why? Sketch the number line regions corresponding to these expressions. List some times for which the code gives an incorrect result.

2. Fix the boolean expression in the above `alert` so that it works.
3. Another approach for comparing times is to keep track of time in total minutes since the beginning of the day. Based on this idea, flesh out the following skeleton so that it works:

.

## Cascading `if` Statements

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.

```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:

```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) {
} else if (grade >= 80) {
} else if (grade >= 70) {
} else if (grade >= 60) {
} else {
}
```

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`.

#### Exercise 3

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.

#### Exercise 4

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.

## Nested `if` Statements

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!

#### Exercise 5

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 Master, while those 18 and over are called Mr.

In the execution box below insert the statements that will assign the correct honorific.

#### Exercise 6

In the two-player game rock/paper/scissors, each player secretly chooses one of three values (`rock`, `paper`, `scissors`) and both players announce their choices at the same time. The rules are:
• `rock` beats `scissors`;
• `scissors` beats `paper`;
• `paper` beats `rock`;
• a tie is declared if both players choose the same value.
1. In the following program skeleton, assume that the variables `p1` and `p2` each hold one of the three strings `"rock"`, `"paper"`, or `"scissors"` for player 1 and player 2, respectively. Flesh out the program so that it pops up an alert box displaying
• `players tie` if the players tie.
• `player 1 wins` if player 1 wins
• `player 2 wins` if player 2 wins

2. Modify the program so that it complains if either player enters an invalid value. .

© Wellesley College Computer Science Staff. This work is licensed under a Creative Commons License. Date Modified: Sunday, 28-Aug-2016 13:04:16 EDT