← Back to JavaScript Course | Chapter 5: ES6+ Features | Lesson 4 of 12

JS ऑप्शनल चेनिंग

Optional chaining आपको किसी चीज़ के अंदर गहराई में देखने देता है बिना crash हुए अगर कोई हिस्सा गायब हो, जैसे किसी cupboard को जांचना और खाली होने पर शालीनता से रुक जाना। आपको error के बजाय undefined मिलता है।
Syntax
javascript
object?.property
object?.[key]
object.method?.()

Basic Optional Chaining

Optional chaining operator ?. किसी property को तभी पढ़ता है जब उससे पहले की हर चीज़ null या undefined न हो, chain में कोई कड़ी गायब होने पर यह error देने के बजाय undefined return करता है।

उदाहरण: Basic Optional Chaining

javascript
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

javascript
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

javascript
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

javascript
const data = null;
console.log(data?.[0]); // undefined

Optional Chaining की सीमाएं

Optional chaining सिर्फ null और undefined से बचाता है, यह दूसरी तरह की errors को चुपचाप निगल नहीं जाता, इसलिए genuine bugs के लिए code को अभी भी normal error handling चाहिए।

उदाहरण: Optional Chaining Limits

javascript
const user = null;
try {
  console.log(user.name.length); // still throws, unrelated bug
} catch (e) {
  console.log("Error:", e.message);
}
Live Example
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. किसी undeclared variable पर ?. इस्तेमाल करना, जो फिर भी ReferenceError throw करता है।
  2. इसके ज़रिए assign करना, जैसे user?.name = "x", जो एक SyntaxError है।
  3. ऐसी values पर ?. का overuse करना जो हमेशा मौजूद रहनी चाहिए, जो undefined return करके असली bugs छुपा देता है।

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.