What is logical assignment (||=, &&=, ??=)?
Operators that assign only when a condition is met.
||= — assign if the current value is falsy.
&&= — assign if the current value is truthy.
??= — assign if the current value is null or undefined.
Great for defaults: config.retries ??= 3.
// ??= — assign if null/undefined (BEST for defaults)
let config = {};
config.timeout ??= 5000; // Sets 5000 (timeout is undefined)
config.retries ??= 3; // Sets 3
let count = 0;
count ??= 10; // Stays 0 (0 is not null/undefined)
// ||= — assign if falsy
let name = '';
name ||= 'Anonymous'; // Sets 'Anonymous' ('' is falsy)
// Probably wrong if '' is a valid value!
// &&= — assign if truthy
let user = { name: 'John' };
user &&= { ...user, lastLogin: new Date() };
// Updates only if user is truthy??= is safest for defaults (preserves 0, '', false). ||= replaces ALL falsy values (may be wrong for 0 and ''). &&= updates only if truthy. The count example shows: 0 ??= 10 keeps 0 (correct), 0 ||= 10 replaces with 10 (probably wrong).
??= is the most useful (defaults without replacing 0/''). Show the 0 example: ??= keeps it, ||= replaces it. &&= for conditional updates.
ES2021 feature.