Please enable JavaScript to use CodeHS

JavaScript Tutorial

Booleans and Logical Operators in JavaScript

Every ride gate at a theme park asks a yes-or-no question: tall enough? Got a ticket? Programs decide the same way, with booleans - and the operators &&, ||, and ! that wire those answers together.

javascript ~20 min Beginner friendly
The Big Idea

What is a boolean?

As programmers, we often need to control exactly when certain lines of code run. We do that with boolean expressions - conditions that evaluate to true or false depending on the state of the program.

Take the statement "it is currently raining." Right now, that statement is either true or false - there is no in-between. Checking it tells you whether to grab an umbrella. JavaScript stores exactly this kind of yes-or-no answer in a special type of variable called a boolean.

A boolean can hold the value true or the value false, and nothing else. Compare that to a number variable, which can hold any number, or a string, which can hold any text. A boolean is like a ride gate at a theme park: it's open, or it's closed.

main.js
let isRaining = true;

console.log("I need to grab my umbrella: " + isRaining);
Console
I need to grab my umbrella: true

Try imagining the value of isRaining flipped to false - the program would print I need to grab my umbrella: false instead. Remember, a boolean can only ever be one of two values! Also notice there are no quotes around true - that matters, as we'll see later.

Lowercase in JavaScript! JavaScript booleans are written true and false, all lowercase. If you've seen Python, it's the opposite convention: Python capitalizes them as True and False. Writing True in JavaScript is an error.


Where Booleans Come From

Comparisons make booleans

You won't always type true or false by hand. Most of the time, a boolean is the answer to a question your program asks with a comparison operator. Every comparison produces a boolean:

OperatorQuestion it asksExampleResult
===Are these two values exactly equal?7 === 7true
!==Are these two values different?3 !== 3false
>Is the left side greater?10 > 4true
<Is the left side smaller?10 < 4false
>=Greater than or equal to?48 >= 48true
<=Less than or equal to?6 <= 5false

That means you can store the answer to a comparison in a boolean variable, just like storing a number:

main.js
let height = 52;

let tallEnough = height >= 48;  // the comparison produces a boolean

console.log("Tall enough for the coaster: " + tallEnough);
Console
Tall enough for the coaster: true

Why three equals signs? JavaScript also has a two-equals ==, but it can give surprising answers because it converts types behind your back (5 == "5" is true!). Stick with === and !== - they only say true when the values really match.


The Power Tools

The logical operators: &&, ||, and !

One condition is often not enough. Extending our weather example: if it's raining we grab an umbrella... but what about these situations?

  • What if it is raining AND it is also cold? Both conditions are true, so we'll need a raincoat as well.
  • What if it is cold AND NOT raining? One condition is true and one is not - so we grab a sweatshirt instead.
  • What if it is sunny? We might still want the umbrella for shade! So if we have rain OR sun, we need the umbrella.

Theme parks work the same way. A big coaster lets you ride if you are tall enough and you have a ticket - one without the other keeps the gate shut. But the carousel might open if you have a ticket or a season wristband - either one works.

JavaScript gives us three logical operators to build these combined conditions. They look like symbols, but read them as words:

&& AND

Evaluates to true only if both values are true. false otherwise.

|| OR

Evaluates to true if at least one value is true. false only when both are false.

! NOT

Flips the value: !true is false, and !false is true. It takes the opposite.

Using them with our weather situations:

  • Raining && cold? → Raincoat
  • Cold && !raining? → Sweatshirt
  • Raining || sunny? → Umbrella

Here's the whole thing as a program. Imagine changing the three booleans at the top and predicting how the output changes:

main.js
let isRaining = true;
let isCold = true;
let isSunny = false;

let raincoat = isRaining && isCold;
let sweatshirt = !isRaining && isCold;
let umbrella = isRaining || isSunny;

console.log("I need to grab my umbrella: " + umbrella);
console.log("I need to grab my raincoat: " + raincoat);
console.log("I need to grab my sweatshirt: " + sweatshirt);
Console
I need to grab my umbrella: true
I need to grab my raincoat: true
I need to grab my sweatshirt: false
Interactive

The ride gate inspector

Time to see the operators in action. The Thunder Coaster has two requirements: riders must be at least 48 inches tall, and they must have a ticket. Drag the height slider and flip the ticket, then watch each gate's expression evaluate live. The coaster gate only swings open when the && row is true - both checks passed!

Ride Gate Inspector

drag the slider, tap the ticket
let height = 52
36 in48 in minimum72 in
height >= 48 → true
hasTicket → true
Thunder Coaster - needs both
height >= 48 && hasTicket
false gate closed
Carousel - either one works
height >= 48 || hasTicket
false gate closed
Ticket booth - the opposite check
!hasTicket
false you already have a ticket
Go get
a ticket!

a && b

abresult
truetruetrue
truefalsefalse
falsetruefalse
falsefalsefalse

a || b

abresult
truetruetrue
truefalsetrue
falsetruetrue
falsefalsefalse

!a

aresult
truefalse
falsetrue

Notice: as you change the slider and ticket, one row in each truth table lights up - that's the row your current values match, where a is height >= 48 and b is hasTicket. The tables are the complete rulebook: every combination of true and false, and what each operator does with it.


Level Up

Combining conditions with parentheses

Boolean expressions can chain together as many conditions as your program needs. When they do, parentheses work just like in math: evaluate what's inside the parentheses first, then combine the results.

Take a && (b || c). JavaScript first works out b || c, gets a single true or false, and then ands it with a. Here's a park example worked out step by step - you can ride if you're tall enough AND you have either a ticket or a wristband:

main.js
let tallEnough = true;
let hasTicket = false;
let hasWristband = true;

// Step 1: (hasTicket || hasWristband) -> (false || true) -> true
// Step 2: tallEnough && true -> true && true -> true
let canRide = tallEnough && (hasTicket || hasWristband);

console.log("You may board the coaster: " + canRide);
Console
You may board the coaster: true

Good to know: even without parentheses, JavaScript has an order of operations for logic: ! first, then &&, then ||. But adding parentheses makes your intent clear to anyone reading your code - use them!


Watch Out

Common mistakes

1. Using = when you mean ===

A single = assigns a value to a variable. Triple === compares two values and produces a boolean. Writing score = 100 when you meant to check the score changes your variable instead of asking a question. If you want the boolean answer, use score === 100.

2. Capitalizing true or false

JavaScript only recognizes lowercase true and false. The capitalized versions crash your program:

main.js
let isSunny = True;  // capital T... uh oh
Console
Uncaught ReferenceError: True is not defined

3. Putting quotes around booleans

"true" with quotes is a string - just four characters of text. It is not the boolean true, and it won't behave like one in your logic. Booleans never wear quotes.

4. Single & or | instead of && and ||

The logical operators are doubled: && and ||. A single & or | is a different operator that works on binary digits, and it will quietly give you numbers instead of booleans. Always double up.


Your Turn

Practice

Setting up and evaluating boolean expressions can range from very simple to rather complex, depending on what your program needs. Let's do some practice so you can perfect your skills!

1

True or False?

The program below starts with four initialized booleans. Before pressing Run, read each expression and predict whether it evaluates to true or false. Hint: just like order of operations in math, evaluate what's inside the parentheses first. Then run it and see how you did!

main.js
let a = true;
let b = false;
let c = true;
let d = false;

let first = a && b && c;
let second = (b || c) || d;
let third = (a || b) && (c || d);
let fourth = !d || b;
let fifth = !a || (b || !c);

console.log("First expression: " + first);
console.log("Second expression: " + second);
console.log("Third expression: " + third);
console.log("Fourth expression: " + fourth);
console.log("Fifth expression: " + fifth);
Console
First expression: false
Second expression: true
Third expression: true
Fourth expression: true
Fifth expression: false
  • a && b && c: every value must be true, but b is false, so the whole chain is false.
  • (b || c) || d: the parentheses give false || true = true, and true || false = true.
  • (a || b) && (c || d): true && true = true.
  • !d || b: !false is true, and true || false = true.
  • !a || (b || !c): !a is false, the parentheses give false || false = false, so false || false = false.
2

Write the Boolean Expressions

How'd you do?? Now go the other direction: turn each everyday statement into a boolean expression. You can create whatever boolean variables you need - this is a pencil-and-paper exercise, not a runnable program. The first one is done for you:

  • You go to the grocery store if you are hungry or need food, and you have enough gas in the car.
    groceryTrip = (hungry || needFood) && carHasGas
  • A self-driving car will turn right if there are no people in the crosswalk and you have enough speed.
  • In order to make cookies, you need to have white or brown sugar, eggs, flour, and all ingredients need to be fresh with no mold.
  • You decide to swim in the water if either the air or water temperature is warm, or you have a wetsuit available.
solutions.js
// 2) "no people" flips the condition with !
turnRight = !peopleInCrosswalk && enoughSpeed

// 3) either sugar works, but everything else is required
makeCookies = (whiteSugar || brownSugar) && eggs && flour && !hasMold

// 4) warm air OR warm water OR a wetsuit - any one is enough
goSwim = (airIsWarm || waterIsWarm) || haveWetsuit

Your variable names can be different - what matters is the logic. Notice how #2 and #3 use ! to say "no people" and "no mold", and how the parentheses in #3 make sure the || gets evaluated before the &&.


Check Yourself

Quick quiz

1. Which of these is a valid boolean value in JavaScript?

2. What does (true && false) || true evaluate to?

3. A rider is 50 inches tall but hasTicket is false. What does height >= 48 && hasTicket evaluate to?

Keep learning JavaScript

Booleans are the fuel that powers every decision in your programs. Next, put them to work: use them to choose between paths with if/else statements, or to keep a loop running while a condition stays true.