Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Type Operators

TypeScript logical assignment (??=, ||=, &&=)

Reference for TypeScript logical assignment operators ??=, ||= and &&=: short-circuit semantics, typing of the result and when to pick each one.

The logical assignment operators combine a logical test with an assignment. a ??= b assigns only if a is null or undefined. a ||= b assigns if a is falsy. a &&= b assigns if a is truthy.

They short-circuit: when no assignment is needed, the right side is not evaluated and the property setter (if any) is not called. This differs from a = a || b, which always performs the assignment.

TypeScript
let name: string | undefined;
name ??= "guest"; // now "guest"

Try it

TypeScript The three operators

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Short-circuit and setters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Syntax

TypeScript
target ??= value
target ||= value
target &&= value
Operator Equivalent Assigns when
a ??= b a ?? (a = b) a is null or undefined
a ||= b a || (a = b) a is falsy
a &&= b a && (a = b) a is truthy

Result type: the expression evaluates to the final value of a. For ??= the type is NonNullable<A> | B. The right side must be assignable to the type of the target, otherwise the usual assignment error appears.

Edge cases: the target must be a variable or property reference (not a call result). Optional chaining on the left (a?.b ??= 1) is a syntax error.

Usage notes

  • Memoization: cache[key] ??= compute(key) is the classic use, as in the example.
  • Pick ??= for defaults of optional fields. ||= would overwrite legitimate 0, "" and false.
  • &&= for conditional updates such as normalizing a value only if it exists.
  • Readonly targets still fail type checks even when the assignment would be skipped at runtime.
  • Narrowing: after x ??= value, TypeScript narrows x to exclude null and undefined when the value type allows it.
  • Availability: since TypeScript 4.0. Older targets get a downleveled form.