AI Hints
Home›JavaScript Tutorial›Text and Truth
JavaScript · Lesson 12 of 138

Booleans

True and false.

⏱ 2 min read▶ Video at 12:55🎓 Free
Watch this lesson in the JavaScript courseWatch on YouTube ↗Full JavaScript course

Is the user logged in? Is the cart empty? Is the password long enough? Programs are full of yes or no questions. JavaScript answers them with booleans, which have just two values. True, and false.

Booleans
From the video: Booleans
  • Logged in? Empty? Long enough?
  • Yes or no questions
  • true and false

Booleans from questions

You can write true or false directly. But usually, booleans come from questions, like comparisons. Is the password's length at least eight? Run it. Comparisons always give a boolean.

app.jsjavascript
const isLoggedIn = true;
const password = "sunshine";

const longEnough = password.length >= 8;
console.log("logged in:", isLoggedIn);
console.log("long enough:", longEnough);
console.log("is 3 bigger than 5?", 3 > 5);
Output
logged in: true
long enough: true
is 3 bigger than 5? false

Naming booleans

A good habit is to name booleans like questions. Is logged in, has items, can edit. Then your code reads almost like English. If is logged in, show the profile. We'll use booleans a lot when we learn if statements.

keyvalue
trueyes
falseno
NamesisX, hasX, canX
Fromcomparisons

Booleans in decisions

Booleans are most useful when they make decisions. Here, can enter is true only if the person has a ticket. If statements, which we'll cover soon, use booleans to choose what to do. And you can flip a boolean with an exclamation mark, which means not. Run it.

app.jsjavascript
const hasTicket = true;
const isMember = false;

const canEnter = hasTicket;
console.log("can enter:", canEnter);
console.log("needs to join:", !isMember);

if (canEnter) console.log("Welcome to the show!");
Output
can enter: true
needs to join: true
Welcome to the show!

Summary

Booleans are true or false, and they usually come from comparisons. Next, all the ways to compare values.

Key takeaways
  • true and false
  • From comparisons
  • Name them like questions
Next up: Comparisons — equal, bigger, smaller