Beginner LevelJavaScript & TypeScript
How do short-circuit evaluation and logical operators (&&, ||, ??) work?
❓ Interview Prompt: Explain short-circuiting with && and ||, operator precedence, and operand return behavior.
Logical operators in JavaScript do not return boolean true/false by default; they return the value of one of their operands:
1. Logical AND (&&):
Evaluates left to right. Returns the first falsy value encountered, or the last operand if all are truthy.
•
Short-circuit: If left is falsy, right is never evaluated.
2. Logical OR (||):
Evaluates left to right. Returns the first truthy value encountered, or the last operand if all are falsy.
•
Short-circuit: If left is truthy, right is never evaluated.
3. Nullish Coalescing (??):
Returns right-hand operand only when left is `null` or `undefined` (ignores falsy 0 or "").
Code Implementation Example
javascript
// && returns first falsy or last item
const a = 'Hello' && 42 && 'World'; // 'World'
const b = 'Hello' && 0 && 'World'; // 0 (short-circuits!)
// || returns first truthy
const user = inputName || 'Anonymous'; // Falls back if inputName is '' or null
// Guard clause pattern with &&
isLoggedIn && renderDashboard(); // Executes function only if isLoggedIn is true
// Difference between || and ??
const count = 0;
const value1 = count || 10; // 10 (because 0 is falsy!)
const value2 = count ?? 10; // 0 (because 0 is NOT null/undefined!)💡Logical AND/OR short-circuit returns and difference between || and ?? for numeric 0.
🎯 Interview Key Takeaway
&& returns the first falsy operand; || returns the first truthy operand. Neither returns a boolean unless operands are booleans.
#Logical Operators#Short Circuit#Control Flow#Beginner
Back to all JavaScript & TypeScript Questions→