Combining Comparisons with &&, || and !

The comparison operators >, <, >= and <= compare two values and give a boolean. >= means "greater than or equal to", and <= means "less than or equal to".

To combine booleans, JavaScript has three logical operators:

OperatorMeansGives true when
&&andboth sides are true
||orat least one side is true
!notthe value is false (it flips it)
const age = 30;
const mayRide = age >= 12 && age <= 65;
const discount = age < 18 || age >= 60;
console.log(mayRide);
console.log(discount);
console.log(!mayRide);

Output:

true
false
false

Age 30 is between 12 and 65, so mayRide is true. It is not under 18 and not 60 or more, so discount is false. And !mayRide flips true to false.

Give your conditions clear names, like mayRide. A name says what the expression means, so the code is easier to read later.

A range needs &&

In math you can write 12 ≤ age ≤ 65. JavaScript lets you write 12 <= age <= 65 too, and it runs without an error. But it does not do what you want:

console.log(12 <= 3 <= 65);
console.log(12 <= 30 <= 65);
console.log(12 <= 200 <= 65);

Output:

true
true
true

All three are true, even for ages 3 and 200. JavaScript works from left to right. First, 12 <= 3 gives false. Then it compares false <= 65. To do that, it changes false to the number 0 (and true to 1). Both 0 and 1 are less than 65, so the answer is always true. Always write a range with &&: age >= 12 && age <= 65.

The right side may not run

&& and || stop as soon as they know the answer. If the left side of && is false, the whole thing is false, so JavaScript does not even look at the right side. This makes code like this safe:

const name = null;
console.log(name !== null && name.length > 2);

Output:

false

name is null, so the left side is false and name.length never runs. That is good, because asking null for its length would stop the program with an error. The next lesson uses this behavior of || to pick default values.

In the exercise, read an age and decide who may ride and who gets a discount, writing the ranges with && and ||.