Logical assignment (??=, ||=, &&=)
Assigns a value only if the variable is nullish, falsy or truthy.
Available since: ES2021
Syntax
a ??= b / a ||= b / a &&= bExamples
Setting a value if there is none yet:
const settings = { theme: null, size: 0 };
settings.theme ??= 'light';
settings.size ??= 14;
console.log(settings);Output:
{
"theme": "light",
"size": 0
}All three operators:
let a = null;
let b = '';
let c = 'Anna';
a ??= 'set by ??=';
b ||= 'set by ||=';
c &&= c.toUpperCase();
console.log(a, '|', b, '|', c);Output:
set by ??= | set by ||= | ANNANotes
a ??= b is short for a ?? (a = b): the assignment happens only when needed.
See also
- Nullish coalescing (??) — Returns the right-hand value if the left is null or undefined.
- Logical OR (||) — Logical OR: returns the first truthy value.
- Logical AND (&&) — Logical AND: returns the first falsy value, or the last one.
In the tutorial
- Logical operators — JavaScript logical operators — AND, OR, NOT, their precedence, default values with || and the ?? operator.