Logical Operators & Short-Circuit
&& and || do not return booleans, they return one of the operands, and that changes how you write code.
Syntax
truthy || fallback
guard && action()The insight most tutorials skip: && and || return one of their operands, not true or false.
a || breturnsaifais truthy, otherwiseb.a && breturnsaifais falsy, otherwiseb.
They also short-circuit: the right side is never evaluated if the left already decides the outcome. That is what makes them safe for guarding expensive or unsafe calls.
const name = user.name || 'Guest'; // fallback
isLoggedIn && renderDashboard(); // guard: only call if truthy
const len = list && list.length; // avoid crashing on nullThe trap
|| treats 0, '', and false as "missing". If those are legitimate values, you want ?? instead (next lesson).
Example
Loading editor…
Press Run to execute the code.
When to use it
- Short-circuit an expensive API call with && so it only runs when the user is authenticated.
- Supply a fallback display name with || when a user's profile name field is an empty string.
- Conditionally render a React component with && so nothing renders when the condition is false.
More examples
AND short-circuit evaluation
AND returns the first falsy value it encounters; if the left side is falsy the right is never evaluated.
const user = { role: "admin" };
const isAdmin = user && user.role === "admin";
console.log(isAdmin); // true – both sides evaluated
const nothing = null && expensiveCall(); // expensiveCall never runsOR for default values
OR returns the first truthy value; used here to fall back to 'Guest' when name is falsy.
function greet(name) {
const display = name || "Guest";
return "Hello, " + display;
}
console.log(greet("Alice")); // "Hello, Alice"
console.log(greet("")); // "Hello, Guest" – empty string is falsyShort-circuit for conditional execution
Uses && as a concise guard: the right side executes only when the left side is truthy.
const DEBUG = true;
DEBUG && console.log("Debug mode active"); // logs only if DEBUG is true
const el = document.getElementById("banner");
el && el.classList.add("hidden"); // safe even if el is null
Discussion