Combine Conditions
JavaScript Logical Operators
`&&`, `||`, and `!` combine conditions. They also have a useful short-circuit behavior you'll see everywhere in real code.
What you'll learn
- Combine conditions with `&&` (AND) and `||` (OR)
- Negate a condition with `!` (NOT)
- Understand short-circuit evaluation
JavaScript has three logical operators:
| Operator | Name | Reads as |
|---|---|---|
&& | AND | both true |
| ` | ` | |
! | NOT | flip the value |
const age = 21;
const hasLicense = true;
console.log(age >= 18 && hasLicense); // true (both true)
console.log(age >= 18 || hasLicense); // true (either true)
console.log(!hasLicense); // false (flip) ▶ Preview: console
Short-Circuit Evaluation
&& and || don’t always evaluate the right side. They short-circuit
as soon as the answer is decided.
a && breturnsaif it’s falsy; otherwiseb.a || breturnsaif it’s truthy; otherwiseb.
console.log("hello" && "world"); // "world" ← first is truthy, return second
console.log("" && "world"); // "" ← first is falsy, return it
console.log("" || "fallback"); // "fallback" ← first is falsy, return second
console.log("hi" || "fallback"); // "hi" ← first is truthy, return it ▶ Preview: console
Defaults With ||
The most common use: provide a fallback when a value is missing.
function greet(name) {
const safe = name || "friend";
console.log(`Hello, ${safe}!`);
}
greet("Ada"); // "Hello, Ada!"
greet(""); // "Hello, friend!"
greet(undefined); // "Hello, friend!" ▶ Preview: console
Guarding With &&
Use && to do something only when a precondition holds.
const user = { name: "Ada", isAdmin: true };
user.isAdmin && console.log("Show admin panel");
// Logs only if isAdmin is true. ▶ Preview: console
This pattern is common in JSX/React for “render this conditionally”.
Precedence
! binds tighter than &&, which binds tighter than ||.
const a = true;
const b = false;
const c = true;
console.log(a && b || c); // true ← (a && b) || c
console.log(a || b && c); // true ← a || (b && c)
console.log(!a && b); // false ← (!a) && b ▶ Preview: console
A Note on Boolean Conversion
!value is the cleanest way to negate. !!value converts to a real
boolean.
console.log(!!"hello"); // true
console.log(!!""); // false
console.log(!!0); // false
console.log(!!{}); // true ← objects are truthy ▶ Preview: console
Up Next
|| falls back on too many things. ?? is more precise.