Logical Operators: AND, OR, NOT

Grade 3, page 7 of 11. A two-minute read.

Sometimes one question isn't enough. You need to combine several. To ride a rollercoaster, you need to be tall enough and have a ticket. To get a discount, you need to be a student or a senior citizen.

JavaScript has three logical operators for combining booleans:

OperatorNameMeaning
&&ANDtrue only if both sides are true
||ORtrue if at least one side is true
!NOTflips true to false and false to true

(The || symbol is two "pipe" characters. On most keyboards, the pipe | is on the same key as the backslash \, above Enter. You'll need Shift to type it.)

AND: &&

Both conditions have to be true:

JavaScript
const height = 140;
const hasTicket = true;

const canRide = height >= 120 && hasTicket;
console.log(canRide);

It prints

true
ABA && B
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

OR: ||

At least one condition has to be true:

JavaScript
const isStudent = false;
const isSenior = true;

const getsDiscount = isStudent || isSenior;
console.log(getsDiscount);

It prints

true
ABA || B
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

NOT: !

! flips a boolean to its opposite. It's like the word "not" in English:

JavaScript
const isRaining = false;
console.log(!isRaining);
console.log(!true);
console.log(!!true);

It prints

true
false
true

!isRaining reads as "not raining," which is true here because it isn't raining. And !!true flips twice, back to true again. (Like saying "I'm not not hungry.")

Combining them

You can combine these operators to ask more complicated questions. Use parentheses to keep things clear:

JavaScript
const age = 25;
const hasLicense = true;
const isDrunk = false;

const canDrive = age >= 18 && hasLicense && !isDrunk;
console.log(canDrive);

const isWeekend = true;
const isHoliday = false;
const isSunny = true;
const goToBeach = (isWeekend || isHoliday) && isSunny;
console.log(goToBeach);

It prints

true
true

Read the second one out loud: "If it's the weekend or a holiday, and it's sunny, go to the beach." Code that reads like a sentence is good code.

Professor’s CornerShort-circuiting

JavaScript is lazy (in a good way). With &&, if the left side is false, the whole thing must be false, so JavaScript doesn't even bother looking at the right side. With ||, if the left side is true, the answer must be true, so it skips the right side. This is called short-circuit evaluation. It sounds like a minor detail, but it enables some very handy tricks that we'll explore in Grade 13.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning