Logical assignment
Learn shortcut logical assignments with &&=, ||= and ??=.
Logical assignment
JavaScript offers three shortcuts that combine logical operators with assignment: &&=, ||= and ??=. They update a variable only when needed and keep code short.
x ||= 5 assigns 5 when x is falsy. x &&= 5 assigns 5 when x is truthy. x ??= 5 assigns 5 when x is null/undefined. Example: config.timeout ??= 3000;. If timeout already has a value it is kept; otherwise it becomes 3000.
When to use each
The three operators assign under different conditions, so you must choose the right one. ||= replaces falsy values, including 0, "" or false. ??= assigns only for null and undefined.
&&= assigns only when the variable is truthy; it is often used to conditionally update an object property. Example: item.inStock &&= true;. If item.inStock exists, it becomes true. Each operator fits a different intent.
Exercise Default with ||=
Set config to { retries: 0 }. Write config.retries ||= 3. Print config.retries.
Show example solution
const config = { retries: 0 };
config.retries ||= 3;
console.log(config.retries);
Exercise Combine all three assignments
Set state to { count: 0, label: null, mode: "on" }. Write state.count ||= 5. Write state.label ??= "Default". Write state.mode &&= "active". Print state.
Show example solution
const state = { count: 0, label: null, mode: "on" };
state.count ||= 5;
state.label ??= "Default";
state.mode &&= "active";
console.log(state);
Test yourself
-
Which operator assigns only for null/undefined?
- ??=
- ||=
- &&=
- =
Show answer
??= — Correct. ??= assigns only for null and undefined.
-
Assign with ??=
const config = { timeout: null }; config.timeout____ 3000; console.log(config.timeout);Show answer
const config = { timeout: null }; config.timeout??= 3000; console.log(config.timeout); -
Match operator to behavior
- ||=
- assigns when falsy
- ??=
- assigns when null/undefined
- &&=
- assigns when truthy
- =
- always assigns