Logical Operators & Short-circuit Evaluation
Logical operators (&&, ||, !) combine conditions and enable short-circuit evaluation — a powerful pattern used in React, default values, and conditional execution throughout professional JavaScript code.
Logical Operators
- && (AND) — Both must be true: age >= 18 && hasLicense. Returns first falsy value, or last value if all truthy
- || (OR) — At least one true: isAdmin || isModerator. Returns first truthy value, or last value if all falsy
- ! (NOT) — Inverts: !true = false, !false = true. !!value converts to boolean
- Short-circuit && — false && anything = false (doesn't evaluate 'anything'). Used for conditional execution
- Short-circuit || — true || anything = true (doesn't evaluate 'anything'). Used for default values
- ?? (Nullish Coalescing) — Like || but only checks null/undefined, not 0 or ''
Logical Operators Code
// AND (&&) — both must be true
const age = 20;
const hasID = true;
console.log(age >= 18 && hasID); // true
// OR (||) — at least one true
const isAdmin = false;
const isMod = true;
console.log(isAdmin || isMod); // true
// NOT (!) — inverts
console.log(!true); // false
console.log(!false); // true
console.log(!!0); // false (convert to boolean)
console.log(!!"hi"); // true
// Short-circuit: Default values
const username = "" || "Guest"; // "Guest" (empty string is falsy)
const port = 0 || 3000; // 3000 (0 is falsy!)
const port2 = 0 ?? 3000; // 0 (?? only checks null/undefined)
// Short-circuit: Conditional execution
const user = { name: "Alice" };
user && console.log(user.name); // "Alice" (runs because user is truthy)
const noUser = null;
noUser && console.log(noUser.name); // doesn't run (prevents error!)Tip
Tip
Use ?? (nullish coalescing) instead of || for default values when 0 or empty string are valid. port || 3000 replaces 0 with 3000, but port ?? 3000 keeps 0. This is critical for configuration values.
?? only checks null/undefined, || checks all falsy.
Common Mistake
Warning
Using || for defaults when 0 or '' are valid values. const count = userCount || 10 replaces 0 with 10, which is wrong if 0 users is a valid state. Use ?? instead: const count = userCount ?? 10.
Practice Task
Note
Practice short-circuit patterns: (1) Use && to safely access user?.address?.city from a possibly null user object. (2) Use || to provide a default username for an empty string. (3) Use ?? to set a default port where 0 is valid.
Quick Quiz
Key Takeaways
- Logical operators (&&, ||,.
- && (AND) — Both must be true: age >= 18 && hasLicense. Returns first falsy value, or last value if all truthy
- || (OR) — At least one true: isAdmin || isModerator. Returns first truthy value, or last value if all falsy
- ! (NOT) — Inverts: !true = false, !false = true. !!value converts to boolean