पाठ 40 / 40
आधुनिक Syntax: Optional Chaining और अन्य
Optional chaining, nullish assignment, at(), structuredClone और private class fields से सुरक्षित, छोटा code लिखें।
Optional chaining
?. किसी के null या undefined होने पर रुककर undefined लौटाता है, और ?? के साथ अच्छा चलता है।
const user = { profile: null };
console.log(user.profile?.name); // undefined, no error
console.log(user.profile?.name ?? "Guest"); // "Guest"
user.settings ??= { theme: "dark" }; // assign only if nullishउपयोगी नए APIs
at() अंत से पढ़ता है, structuredClone deep copy करता है, और #private fields class internals छिपाते हैं।
const arr = [10, 20, 30];
console.log(arr.at(-1)); // 30
const copy = structuredClone({ a: { b: 1 } });
class Account {
#balance = 0;
deposit(n) { this.#balance += n; }
get balance() { return this.#balance; }
}?. का उपयोग optional data की सुरक्षा के लिए करें, असली bugs छिपाने के लिए नहीं। Deep copies के लिए JSON.parse(JSON.stringify(x)) की जगह structuredClone उपयोग करें।
त्वरित जाँच
त्वरित जाँच: profile के null होने पर user.profile?.name क्या लौटाता है?
- undefined
- A TypeError
- null
- ""
Answer
undefined — Optional chaining short-circuit होकर undefined लौटाता है।