AI Hints
JavaScript · Lesson 21 of 138

Logical Operators

&&, ||, !.

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

Can you ride the roller coaster? You must be tall enough, and old enough. Can you get a discount? You must be a student, or a senior. Logical operators combine conditions like these.

Logical Operators
From the video: Logical Operators
  • Tall enough and old enough?
  • Student or senior?
  • Combine conditions

And, or, not

Two ampersands mean and. Both sides must be true. Two vertical bars mean or. At least one side must be true. And an exclamation mark means not, which flips true to false. Run it.

app.jsjavascript
const age = 15;
const height = 150;
const isStudent = true;

console.log("ride:", age >= 12 && height >= 140);
console.log("discount:", isStudent || age >= 65);
console.log("not a student:", !isStudent);
Output
ride: true
discount: true
not a student: false

Truth table

Here's every combination. And is only true when both sides are true. Or is true when either side is true, or both. And not simply flips the value. JavaScript also stops early. If the left side of and is false, it doesn't even check the right side.

aba && ba || b
truetruetruetrue
truefalsefalsetrue
falsetruefalsetrue
falsefalsefalsefalse

Short-circuiting

And and or stop early, which is called short circuiting. If the left side of and is false, the right side never runs. If the left side of or is true, the right side is skipped. That's why or is often used for fallback values, like a default name. Run it.

app.jsjavascript
const user = null;

console.log(user && user.name);

const typed = "";
const name = typed || "Guest";
console.log("Hello,", name);

console.log(true || console.log("this never runs"));
Output
null
Hello, Guest
true

Summary

And needs both, or needs either, and not flips the value. Next, how JavaScript decides what counts as true.

Key takeaways
  • && both
  • || either
  • ! flips
Next up: Truthy and Falsy — what counts as true