Smart Operators
The && (AND) and || (OR) operators in JavaScript work on the principle of " short-circuiting " . They stop evaluation as soon as the result becomes clear.
1. OR (||) seeks the FIRST TRUTHY
It returns the first true value encountered (or the last value if no truth is found).
let name = username || "Anonymous";
// If username is an empty string or null, we assign "Anonymous"
2. AND (&&) seeks the FIRST FALSY
It returns the first false value encountered (or the last value if all are true).
isAdmin && alert("Hello, admin!");
// alert will only trigger if isAdmin === true
3. Difference from Nullish (??)
Remember: || considers 0, false, and "" as false. If these values are valid for you, use ??.
Tip
Short-circuiting is often used for safe access to nested properties (before the ?. operator existed): user && user.address && user.address.city.
Caution
Don't make chains too long — such code is hard to read and debug.