Boolean Operations
Combining Booleans
JavaScript combines true and false values with three operators:&& for "and", || for "or", and ! for "not". They are punctuation rather than words, and the doubling is not optional. A single & or a single | is a different operator that works on the bits of a number.The two values themselves are spelled
true and false, lowercase, always.| p | q | p || q |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
| p | q | p && q |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
| p | !p |
|---|---|
| true | false |
| false | true |
The short way to read the three tables:
&& is true only when BOTH sides are true, so its column has a single true row. || is false only when BOTH sides are false, so its column has a single false row. ! has nothing to combine, it flips whatever it is handed.The program below decides whether a scooter can be rented: its battery has to be charged enough, and the rider has to have a helmet. Run it, then make each change below and run it again. Press Reset before each change, so that each one starts from the original program.
• Set
helmet to false.• Set
battery to 54.• Set
battery to 54 and helmet to false.let battery = 82;
let helmet = true;
let charged = battery >= 65;
console.log("Charged:", charged);
console.log("Charged and helmet:", charged && helmet);
console.log("Charged or helmet:", charged || helmet);
console.log("Battery too low:", !(battery >= 65));
Output
Press Run to see what this program prints.
Note: This IDE is for experimenting with the code in this lesson. Your changes are not saved, and refreshing the page puts back the original lesson code.