Logical Operators & Short-Circuit

&& and || do not return booleans, they return one of the operands, and that changes how you write code.

Syntaxtruthy || fallback guard && action()

The insight most tutorials skip: && and || return one of their operands, not true or false.

  • a || b returns a if a is truthy, otherwise b.
  • a && b returns a if a is falsy, otherwise b.

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 null

The trap

|| treats 0, '', and false as "missing". If those are legitimate values, you want ?? instead (next lesson).

Example

Try it yourself
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.

Example · js
const user = { role: "admin" };
const isAdmin = user && user.role === "admin";
console.log(isAdmin); // true – both sides evaluated
const nothing = null && expensiveCall(); // expensiveCall never runs

OR for default values

OR returns the first truthy value; used here to fall back to 'Guest' when name is falsy.

Example · js
function greet(name) {
  const display = name || "Guest";
  return "Hello, " + display;
}
console.log(greet("Alice")); // "Hello, Alice"
console.log(greet(""));      // "Hello, Guest" – empty string is falsy

Short-circuit for conditional execution

Uses && as a concise guard: the right side executes only when the left side is truthy.

Example · js
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

  • Be the first to comment on this lesson.
Logical Operators & Short-Circuit — JavaScript | SoundsCode