JS Logical Assignment
In this page:
AND Assignment
&&= only assigns the right-hand value if the variable is currently truthy — equivalent to a && (a = b), useful for updating a value only when it already exists and is meaningful.
Example: AND Assignment
let session = "active";
session &&= "updated";
console.log(session);
OR Assignment
||= only assigns if the variable is currently falsy — equivalent to a || (a = b), a compact way to set a default when a variable hasn't been given a real value yet, though it also overwrites legitimate falsy values like 0 or an empty string.
Example: OR Assignment
let name = "";
name ||= "Guest";
console.log(name);
Nullish Assignment
??= only assigns if the variable is currently null or undefined — equivalent to a ?? (a = b), the safest of the three for setting defaults without touching legitimate falsy values like 0.
Example: Nullish Assignment
let count = 0;
count ??= 10;
console.log(count); // 0, unaffected
Practical Defaults
These operators are especially handy for filling in missing object properties or config defaults in one line, instead of writing an explicit if-check before the assignment.
Example: Practical Defaults
const config = {};
config.timeout ??= 3000;
console.log(config.timeout);
Choosing the Right Operator
Pick based on what counts as missing: use ??= when only null/undefined should trigger a default, ||= when any falsy value should, and &&= when you only want to update an already-set value.
Example: Choosing the Right Operator
let a; a ??= 1; console.log(a); // null/undefined only
let b = 0; b ||= 2; console.log(b); // any falsy
let c = "x"; c &&= "y"; console.log(c); // only if truthy
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: