Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Logical assignment (??=, ||=, &&=)

Assigns a value only if the variable is nullish, falsy or truthy.

Available since: ES2021

Syntax

a ??= b / a ||= b / a &&= b

Examples

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 ||= | ANNA

Notes

a ??= b is short for a ?? (a = b): the assignment happens only when needed.

See also

In the tutorial

  • Logical operators — JavaScript logical operators — AND, OR, NOT, their precedence, default values with || and the ?? operator.

Thanks for reading!

Donate to the site — we work hard for you.