JS Logical Assignment
In this page:
a ||= b; // assign if a is falsy
a &&= b; // assign if a is truthy
a ??= b; // assign if a is null/undefined
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.
उदाहरण: AND Assignment
// Declare the variable `session`, set to "active"
// Declare the variable `session`, set to "active"
let session = "active";
session &&= "updated";
// Print `session` to the console
// Print `session` to the console
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.
उदाहरण: OR Assignment
// Declare the variable `name`, set to ""
// Declare the variable `name`, set to ""
let name = "";
name ||= "Guest";
// Print `name` to the console
// Print `name` to the console
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.
उदाहरण: 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.
उदाहरण: Practical Defaults
// Declare the constant `config`, set to `{}`
// Declare the constant `config`, set to `{}`
const config = {};
config.timeout ??= 3000;
// Print `config.timeout` to the console
// Print `config.timeout` to the console
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.
उदाहरण: 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: