Chapter IV · Operators & Expressions
Logical Operators
Logical operators (&&, ||, !) combine or invert boolean conditions — and in JavaScript, && and || do something extra: they return one of their actual operands, not just true/false.
01 What Are Logical Operators?
&& means "and," || means "or," ! means "not." They exist to build compound conditions — "logged in AND has permission," "cached OR fetched fresh" — out of simpler ones.
What makes JavaScript's version distinctive: && and || are short-circuiting. They stop evaluating as soon as the outcome is determined, and they return the actual operand value that decided the outcome, not a plain boolean.
02 Simple Example
Short-circuit evaluation returning a real value, not just true/false.
const username = '' || 'Guest'; // 'Guest' — '' is falsy, so the right side is used
const isAdmin = true && 'Access granted'; // 'Access granted'
console.log(!true); // false
03 How It Works
For a && b: if a is falsy, JavaScript never evaluates b at all — it just returns a. If a is truthy, it evaluates and returns b. || works the same way in reverse: return the left side if it's truthy, otherwise evaluate and return the right.
Short-circuiting: the right operand is only evaluated when it needs to be.
04 Production Example
Guarding a function call so it only runs when a callback actually exists — a very common real-world use of short-circuiting.
function notifyUser(onComplete) {
const taskFinished = true;
taskFinished && onComplete?.(); // only calls onComplete if it was provided
}
05 Mental Model
"A bouncer checking a guest list in order — the moment one check fails (&&) or succeeds (||), it stops checking and gives its answer immediately."
06 Best Practices
- Prefer
??over||for defaults when0,'', orfalseare valid, meaningful values you don't want overwritten. - Using
&&for side effects (like the notification example) is idiomatic in small doses, but a realifis clearer once the logic grows past one line.
07 Interview Questions
Q: What does true && 'hello' evaluate to, and why?
'hello' — && returns the second operand once the first is confirmed truthy, not a plain boolean.
Q: Why can short-circuiting matter beyond just readability?
The right-hand side is never evaluated if short-circuited — useful (and sometimes necessary) when that side has side effects or could throw, like accessing a property on something that might not exist.
Key Takeaway
&& and || short-circuit and return an actual operand, not just true/false — which makes them useful for defaults and conditional calls, but worth using deliberately.