ऑप्शनल चेनिंग ऑपरेटर ES2020 में पेश किया गया था और यह हमें प्रत्येक रेफरेंस की स्पष्ट रूप से जांच किए बिना नेस्टेड प्रॉपर्टी तक पहुँचने की अनुमति देता है कि वह null या undefined है या नहीं। पहले, हम && ऑपरेटर का उपयोग करके जांचते थे कि पैरेंट ऑब्जेक्ट null या undefined नहीं है, लेकिन अब हम '?.' ऑप्शनल चेनिंग ऑपरेटर का उपयोग कर सकते हैं।
जावास्क्रिप्ट में ऑप्शनल चेनिंग ऑपरेटर के लिए निम्नलिखित कोड है:
उदाहरण
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .result { font-size: 20px; font-weight: 500; color: blueviolet; } </style> </head> <body> <h1>Optional Chaining operator in JavaScript</h1> <div class="result"></div> <br /> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to use optional chaining operator to access person object properties</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let person = { name: "Rohan", location: { state: "Delhi", country: "India", }, }; BtnEle.addEventListener("click", () => { resEle.innerHTML = "person ?. location ?. state = " + person?.location?.state + "<br>"; resEle.innerHTML +="person ?. location ?. country = " +person?.location?.country +"<br>"; resEle.innerHTML +="person ?. personalDetails ?. birthDate = " + person?.personalDetails?.birthDate +"<br>"; }); </script> </body> </html>
आउटपुट

'CLICK HERE' बटन पर क्लिक करने पर:
