Short-Circuit Tricks

Grade 13, page 7 of 12. A one-minute read.

In Grade 3, the Professor mentioned that && and || are "lazy": they stop as soon as they know the answer. This is called short-circuiting, and it enables a few tricks you'll see in other people's code.

&& as a mini if

a && b only looks at b if a is truthy. So you can use it to run something only if a condition is true:

JavaScript
const isLoggedIn = true;
const isAdmin = false;

isLoggedIn && console.log("Welcome back!");
isAdmin && console.log("You have admin powers.");

It prints

Welcome back!

It works, but honestly, a plain if statement is usually clearer. You'll mostly see this trick in frameworks like React.

What && and || actually return

Here's a secret: && and || don't always return true or false. They return one of the actual values:

  • a || b returns a if a is truthy, otherwise b.
  • a && b returns a if a is falsy, otherwise b.
JavaScript
console.log("pizza" || "salad");
console.log("" || "salad");
console.log("pizza" && "salad");
console.log(0 && "salad");

It prints

pizza
salad
salad
0

That's exactly why userName || "Guest" works as a default!

Logical assignment: ||=, &&=, ??=

These combine a logical operator with assignment, just like += combines + with assignment:

JavaScript
const config = { retries: 0, title: "" };

config.retries ??= 3;    // only assign if null/undefined
config.title ||= "Untitled"; // assign if falsy
config.timeout ??= 5000; // missing, so it gets assigned

console.log(config);

It prints

{ retries: 0, title: 'Untitled', timeout: 5000 }

x ??= y means "if x is null or undefined, set it to y." It's a tidy way to fill in missing settings without overwriting ones that already exist.

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning