Short-circuit evaluation
Learn how && and || short-circuit values and the patterns based on it.
Short-circuit evaluation
In JavaScript && (and) and || (or) do not just return true/false; they return one of the two values. This behavior is called short-circuit evaluation.
&& returns the left side when it is falsy, otherwise the right side: 0 && "x" gives 0. || returns the left side when it is truthy, otherwise the right side: "a" || "b" gives "a". So || sets defaults and && guards access.
Default and guard patterns
Short-circuit is used in two common patterns. First, a default value: const name = input || "Guest";. When input is empty, name becomes "Guest" automatically.
Second, a guard: user && user.name. If user is null or undefined, && returns the left side and user.name is never accessed, so no error occurs. When user exists, the right side runs and the name is returned.
Exercise Default value pattern
Set userName to an empty string "". Set displayName to userName || "Guest". Print displayName.
Show example solution
const userName = "";
const displayName = userName || "Guest";
console.log(displayName);
Exercise Guard pattern
Set user to the object { name: "Alex" }. Set name to user && user.name. Print name.
Show example solution
const user = { name: "Alex" };
const name = user && user.name;
console.log(name);
Test yourself
-
What does "" || "Guest" evaluate to?
"" || "Guest"- ""
- "Guest"
- true
- false
Show answer
"Guest" — Correct. The left side is an empty string (falsy), so || returns the right side.
-
Give a default value
const userName = ""; const displayName = userName ____ "Guest"; console.log(displayName);Show answer
const userName = ""; const displayName = userName || "Guest"; console.log(displayName); -
Match expression to result
- 0 || "x"
- "x"
- "a" && "b"
- "b"
- null || 5
- 5
- 0 && "y"
- 0