Logical Assignment Operators Guard Defaults
??= writes only for nullish values, ||= for falsy ones and &&= for truthy ones, and the right-hand expression is skipped entirely when the guard fails.
Code
// ??= 只在 null/undefined 时写入;||= 只在假值时写入;&&= 只在真值时写入
const opts = { host: '', port: 0, retries: 3, tags: null };
opts.host ??= 'localhost'; // '' 不是 nullish:保持原值
opts.port ||= 8080; // 0 是假值:被覆盖
opts.retries ||= 5; // 3 是真值:不动
opts.tags ??= []; // null 是 nullish:补默认
console.log('after guards:', JSON.stringify(opts));
// &&= 反过来:字段为真值时才覆盖,适合"只在已设置时收紧"
const policy = { level: 'warn', locked: '' };
policy.level &&= 'error';
policy.locked &&= 'on';
console.log('after tighten:', JSON.stringify(policy));
// 赋值只发生在需要时:右边的表达式不会被求值
let evaluations = 0;
function expensive() {
evaluations += 1;
return 'computed';
}
const cached = { value: 'present' };
cached.value ??= expensive();
const empty = {};
empty.value ??= expensive();
console.log('right side evaluated', evaluations, 'time(s):', cached.value, empty.value);Output
Captured from a sandboxed run of this snippet in the build pipeline.
after guards: {"host":"","port":8080,"retries":3,"tags":[]}
after tighten: {"level":"error","locked":""}
right side evaluated 1 time(s): present computedInside the snippet
The compressed view: all the work sits in the function expensive, doing all the work.
Caveats
- No third-party code is loaded at any point while this runs.
Using it
Signature: function expensive()
The demo output is labeled (after guards:, after tighten:, right side evaluated), so the printed output reads as a trace of the operations performed.
Key statements
opts.host ??= 'localhost'; // '' 不是 nullish:保持原值
opts.port ||= 8080; // 0 是假值:被覆盖
opts.retries ||= 5; // 3 是真值:不动
opts.tags ??= []; // null 是 nullish:补默认
console.log('after guards:', JSON.stringify(opts));
cached.value ??= expensive();
empty.value ??= expensive();
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- Does the runtime need any help from npm, pip, cargo, or the like?
- No — the package manager has nothing to do here; nothing is declared. The file defines `expensive` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.