JS लॉजिकल असाइनमेंट
a ||= b; // assign if a is falsy
a &&= b; // assign if a is truthy
a ??= b; // assign if a is null/undefined
AND Assignment
&&= दाईं तरफ की value सिर्फ तभी assign करता है जब variable अभी truthy हो — a && (a = b) के बराबर, यह किसी value को सिर्फ तभी update करने के लिए उपयोगी है जब वह पहले से मौजूद और सार्थक हो।
उदाहरण: 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
||= सिर्फ तभी assign करता है जब variable अभी falsy हो — a || (a = b) के बराबर, यह तब एक default सेट करने का एक compact तरीका है जब किसी variable को अभी तक कोई असली value न मिली हो, हालांकि यह 0 या खाली string जैसी असली falsy values को भी overwrite कर देता है।
उदाहरण: 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
??= सिर्फ तभी assign करता है जब variable अभी null या undefined हो — a ?? (a = b) के बराबर, 0 जैसी असली falsy values को छुए बिना defaults सेट करने के लिए यह तीनों में सबसे सुरक्षित है।
उदाहरण: Nullish Assignment
let count = 0;
count ??= 10;
console.log(count); // 0, unaffected
Practical Defaults
ये operators एक line में गायब object properties या config defaults भरने के लिए खासतौर पर काम आते हैं, assignment से पहले एक explicit if-check लिखने के बजाय।
उदाहरण: 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);
सही Operator चुनना
यह चुनें कि 'गायब' किसे माना जाए: ??= इस्तेमाल करें जब सिर्फ null/undefined को ही default trigger करना चाहिए, ||= जब कोई भी falsy value करे, और &&= जब आप सिर्फ पहले से सेट value को update करना चाहते हों।
उदाहरण: 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
- यह उम्मीद करना कि
a ||= bहमेशा चलेगा, जबकि यह सिर्फ तब assign करता है जबafalsy हो। 0या""valid values होने पर||=इस्तेमाल करना, जो उन्हें overwrite कर देता है;??=इस्तेमाल करें।- किसी
constपर logical assignment इस्तेमाल करना, जो एक assignment होने परTypeErrorthrow करता है।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: