JS ऑप्शनल चेनिंग
In this page:
object?.property
object?.[key]
object.method?.()
Basic Optional Chaining
Optional chaining operator ?. किसी property को तभी पढ़ता है जब उससे पहले की हर चीज़ null या undefined न हो, chain में कोई कड़ी गायब होने पर यह error देने के बजाय undefined return करता है।
उदाहरण: Basic Optional Chaining
const user = {};
console.log(user?.name); // undefined, no error
Nested Properties
Optional chaining गहराई से nested data के लिए खासतौर पर उपयोगी है, जैसे user?.address?.city, जहाँ user, address, या city में से कोई भी अभी मौजूद न हो, हर property access से पहले manual null checks की एक लंबी chain से बचते हुए।
उदाहरण: Nested Properties
const user = { address: {} };
console.log(user?.address?.city); // undefined
Optional Method Calls
?. किसी function call से पहले भी काम करता है, जैसे obj.method?.() में, इसलिए method मौजूद न होने पर call को safely skip कर दिया जाता है, TypeError देने के बजाय — यह उन optional callbacks के लिए उपयोगी है जो शायद दिए ही न गए हों।
उदाहरण: Optional Method Calls
const obj = {};
console.log(obj.greet?.()); // undefined, skipped safely
Optional Array Access
वही operator ?.[index] के साथ array-style access में भी काम करता है, जो आपको किसी ऐसी array से एक item safely पढ़ने देता है जो खुद null या undefined हो सकती है, पहले अलग से array के मौजूद होने की जांच किए बिना।
उदाहरण: Optional Array Access
const data = null;
console.log(data?.[0]); // undefined
Optional Chaining की सीमाएं
Optional chaining सिर्फ null और undefined से बचाता है, यह दूसरी तरह की errors को चुपचाप निगल नहीं जाता, इसलिए genuine bugs के लिए code को अभी भी normal error handling चाहिए।
उदाहरण: Optional Chaining Limits
const user = null;
try {
console.log(user.name.length); // still throws, unrelated bug
} catch (e) {
console.log("Error:", e.message);
}
- किसी undeclared variable पर
?.इस्तेमाल करना, जो फिर भीReferenceErrorthrow करता है। - इसके ज़रिए assign करना, जैसे
user?.name = "x", जो एकSyntaxErrorहै। - ऐसी values पर
?.का overuse करना जो हमेशा मौजूद रहनी चाहिए, जोundefinedreturn करके असली bugs छुपा देता है।
Chapter Quiz — Complete all 12 topics to unlock
0/12 topics done
Complete these topics first: