<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Rahul Dhiman</title>
    <description>The latest articles on DEV Community by Rahul Dhiman (@rdrahuldhiman).</description>
    <link>https://dev.to/rdrahuldhiman</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F572327%2F1e20c3c8-e617-42d3-95d2-800eb37714e0.png</url>
      <title>DEV Community: Rahul Dhiman</title>
      <link>https://dev.to/rdrahuldhiman</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/rdrahuldhiman"/>
    <language>en</language>
    <item>
      <title>What is optional chaining and why you should use it?</title>
      <dc:creator>Rahul Dhiman</dc:creator>
      <pubDate>Sun, 13 Mar 2022 17:16:58 +0000</pubDate>
      <link>https://dev.to/rdrahuldhiman/what-is-optional-chaining-and-why-you-should-use-it-1g05</link>
      <guid>https://dev.to/rdrahuldhiman/what-is-optional-chaining-and-why-you-should-use-it-1g05</guid>
      <description>&lt;p&gt;Hello my fellow coders, In this blog I'm gonna discuss what exactly optional chaining is and why you should use it. &lt;/p&gt;

&lt;p&gt;Below is the definition of &lt;strong&gt;Optional Chaining&lt;/strong&gt; from MDN:  &lt;/p&gt;

&lt;p&gt;"The &lt;strong&gt;optional chaining operator&lt;/strong&gt; (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid."&lt;/p&gt;

&lt;p&gt;So it simply means that with an optional chaining operator which looks like this &lt;strong&gt;"?."&lt;/strong&gt; we can actually look into an object's property's value and check if it is &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt;. &lt;br&gt;
If the value is anything other than &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt; then it will return the value or move further in the chain else instead of throwing an error it will stop the further evaluation and return &lt;code&gt;undefined&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;Let's go through an example if my explanation made it more confusing.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;let person ={
name:"Rahul",
surname: "Dhiman",
address : {
state: "Maharashtra",
city: "Mumbai",
pinCode: 100000
},
getCity : function(){ return `${this.address.city}`},
likes:["JavaScript","React","React Native"]
}
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Let's understand how optional chaining works with this &lt;code&gt;person&lt;/code&gt; object.&lt;br&gt;
Here if we want to access &lt;code&gt;person.address.city&lt;/code&gt; this is how we would do it with  &lt;code&gt;.&lt;/code&gt; (dot) operator.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;console.log(person.address.city)
//expected output: Mumbai
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;But here what would happen if there is no &lt;code&gt;address&lt;/code&gt; property present in a &lt;code&gt;person&lt;/code&gt; object.&lt;br&gt;
Let's run the code in the console and check the output&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--ibJ8IJFs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8y8gmhd3cx9a8hgpo15d.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--ibJ8IJFs--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8y8gmhd3cx9a8hgpo15d.png" alt="Getting error. cannot read properties of undefined" width="880" height="363"&gt;&lt;/a&gt;&lt;br&gt;
It’s like saying I want to debug my code without using console.logs. &lt;br&gt;
I just tried to make laugh. Did you laugh?&lt;br&gt;
Under the hood probably this is how it would work.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--EJ3IaSh---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hlwuj7k6boavbdvsck8.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--EJ3IaSh---/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4hlwuj7k6boavbdvsck8.png" alt="Table that shows how JS Engine runs code with dot operator" width="880" height="355"&gt;&lt;/a&gt;&lt;br&gt;
So here is when the JS engine evaluates &lt;code&gt;person.address&lt;/code&gt; then it finds nothing and evaluates to  &lt;code&gt;undefined&lt;/code&gt; which is fine since it is actually undefined (not defined in &lt;code&gt;person&lt;/code&gt; object)&lt;br&gt;
And then when JS engine checks for &lt;code&gt;city&lt;/code&gt; property on &lt;code&gt;undefined&lt;/code&gt; and then it goes crazy because undefined data type is not meant to store properties in it and accessing them using dot operator is unexpected and the compiler throws an error.&lt;br&gt;
Now how we can fix it using the optional chaining operator &lt;strong&gt;?.&lt;/strong&gt;&lt;br&gt;
The answer lies within the question.&lt;br&gt;
Let's the run same code using optional chaining and see what we get.&lt;br&gt;&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--Wj9dNO4j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r343bvo1jdadhhshwfge.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--Wj9dNO4j--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/r343bvo1jdadhhshwfge.png" alt="Code example using optional chaining operator. Here we don't get any error" width="816" height="220"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here it is checking the &lt;code&gt;address&lt;/code&gt; for null or undefined and since it's undefined it stops further evaluation and returns undefined. So we are actually not even executing &lt;code&gt;person.address.city&lt;/code&gt; part. Optional chaining operator will check for &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt; for the preceding key only&lt;/p&gt;

&lt;p&gt;Let's go through the table again.&lt;br&gt;
&lt;a href="https://res.cloudinary.com/practicaldev/image/fetch/s--nnUuB9WN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2163wpqcwllgjph80lmn.png" class="article-body-image-wrapper"&gt;&lt;img src="https://res.cloudinary.com/practicaldev/image/fetch/s--nnUuB9WN--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2163wpqcwllgjph80lmn.png" alt="Table that shows how JS Engine runs code with optional chaining operator" width="880" height="353"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Here we can see that person.address?.&lt;strong&gt;city&lt;/strong&gt; part never gets executed so it does not throw an error and returns undefined.&lt;br&gt;
Optional chaining operator is also quite helpful when we are running array or object specific methods.&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;const testObj = {name:"Rahul",surname:"Dhiman"};

testObj.forEach(elememt =&amp;gt; console.log(elememt));
//throws error: "obj.forEach is not a function" 😩
testObj.forEach?.(element =&amp;gt; console.log(element));
// No errors 😎
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;In the above example optional chaining operator is checking what &lt;code&gt;forEach&lt;/code&gt; is evaluating to and since it is undefined it shot circuits and stops further execution and we don't get an error.&lt;/p&gt;

&lt;p&gt;This is how we can make use of optional chaining operators while working with array or object methods.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;The key point to remember:&lt;/strong&gt;&lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;Optional chaining operator only checks for &lt;code&gt;null&lt;/code&gt; or &lt;code&gt;undefined&lt;/code&gt; not all &lt;code&gt;falsy&lt;/code&gt; types.&lt;/li&gt;
&lt;li&gt;Optional chaining operator evaluates the property preceding the operator not the one present after operator eg. person.address?.city
&lt;/li&gt;
&lt;/ol&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;person.address?.city
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;Here address property is being checked by the optional chaining operator since in the call chain it comes exactly before the optional chaining operator and person object is not being checked. &lt;/p&gt;

&lt;ol&gt;
&lt;li&gt;After evaluation, if the value is null or undefined then the optional chaining operator returns undefined and stops further execution.&lt;/li&gt;
&lt;li&gt;optional chaining operator can be used in the following constructs

&lt;ol&gt;
&lt;li&gt;
&lt;code&gt;obj?.prop&lt;/code&gt; – returns &lt;code&gt;obj.prop&lt;/code&gt; if &lt;code&gt;obj&lt;/code&gt; exists, otherwise &lt;code&gt;undefined&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;obj?.[prop]&lt;/code&gt; – returns &lt;code&gt;obj[prop]&lt;/code&gt; if &lt;code&gt;obj&lt;/code&gt; exists, otherwise &lt;code&gt;undefined&lt;/code&gt;.&lt;/li&gt;
&lt;li&gt;
&lt;code&gt;obj.method?.()&lt;/code&gt; – calls &lt;code&gt;obj.method()&lt;/code&gt; if &lt;code&gt;obj.method&lt;/code&gt; exists, otherwise returns &lt;code&gt;undefined&lt;/code&gt;
&lt;/li&gt;
&lt;/ol&gt;


&lt;/li&gt;
&lt;/ol&gt;

&lt;p&gt;Conclusion: Optional chaining operator is a great JavaScript feature that can be used to make our lives easier and code cleaner.&lt;/p&gt;

</description>
    </item>
  </channel>
</rss>
