Logical Assignment ??= &&= ||=

Assign only when a condition holds, in one short-circuiting operator.

Syntaxa ||= b a &&= b a ??= b

ES2021 fused logical operators with assignment. Each one assigns only if its logical test would proceed, and each short-circuits so the right side is skipped otherwise.

OperatorAssigns when left is...Long form
a ||= bfalsya || (a = b)
a &&= btruthya && (a = b)
a ??= bnull / undefineda ?? (a = b)

The nuance that matters

They short-circuit the assignment itself. obj.x ??= compute() does not even call compute() if obj.x already has a value, and it does not trigger setters. That makes ??= the cleanest lazy-initialise / memo primitive.

cache[key] ??= expensive(key);   // compute once, reuse after

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Use ??= to lazily assign a default timeout to a config object only if the key is absent.
  • Use ||= to set a fallback username when the stored value is an empty string.
  • Use &&= to update a cached result only when the cache entry already exists.

More examples

Nullish assignment ??=

??= assigns only when the current value is null or undefined, preserving the intentional 0 for port.

Example Β· js
const cfg = { port: 0 };
cfg.host ??= "localhost";
cfg.port ??= 3000; // 0 is not null/undefined, kept
console.log(cfg); // { port: 0, host: "localhost" }

OR assignment ||=

||= assigns the right-hand side when the left is falsy, providing a fallback for empty strings.

Example Β· js
let username = "";
username ||= "Anonymous";
console.log(username); // "Anonymous" – empty string is falsy

AND assignment &&=

&&= replaces the left side only when it is already truthy, useful for enriching existing values.

Example Β· js
const cache = { user: { name: "Alice" } };
cache.user &&= { ...cache.user, lastSeen: Date.now() };
console.log(cache.user.name); // "Alice" – updated in place

Discussion

  • Be the first to comment on this lesson.
Logical Assignment ??= &&= ||= β€” JavaScript | SoundsCode