Optional chaining operator in JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

The optional chaining operator is introduced in ES2020 and allows us to access a nested property without checking explicitly if each reference in the chain is null or undefined. Earlier, we used to use && operator to check if the parent object isn’t null or undefined but now we can use the ‘?.’ optional chaining operator.

Following is the code for optional chaining operator in JavaScript −

Example

 Live Demo

<!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>

Output

On clicking the ‘CLICK HERE’ button −

raja
Published on 20-Jul-2020 08:31:30
Advertisements