One Operator ? : Three Concepts
Published: 2023-04-04 16:20:00

<p>Hello there, my dear friend! Are you tired of writing long, repetitive, and confusing code just to handle null values in JavaScript? writing endless if-else statements for the edge cases? Does your codespace is full of error handlers?</p>
<p>Fear not! In this blog, <em>our company</em> <em>will</em> (: <mark>what company, there is no company, you work for your own dude</mark> : <mark>oh yah sorry</mark>) Scratch that my friend, <em>I</em> will make sure from this moment, you will be writing super effective code without smashing your head (: <mark>everyone is not like you, they write better code</mark> : <mark>hmm ok</mark>)</p>
<p>So, buckle up and get ready to experience three superheroes of the coding world = <em>Batman, Superman, Wonder woman</em> (: <mark>man get out of DC, you are writing a Javascript blog</mark> : <mark>Oh F, sorry</mark>). Pardon my friend, they are = <strong>Ternary Operator, Optional Chaining, and Nullish Coalescing</strong></p>
<h3 id="heading-ternary-operator">Ternary Operator :</h3>
<p>The ternary operator is a shorthand version of an if-else statement. It allows us to write a simple one-line code for conditional statements. The syntax for a ternary operator is</p>
<pre><code class="lang-javascript">(condition) ? expressionIfTrue : expressionIfFalse
</code></pre>
<p>Here is a function that checks two numbers and returns which one is a greater</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> compare = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> (a &gt; b) ? <span class="hljs-string">"a is greater"</span> : <span class="hljs-string">"b is greater"</span>;
</code></pre>
<p>But what if, there is a scenario where we just have to return <code>true</code> or <code>false.</code> You be like simple, do it like this</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> compare = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> (a &gt; b) ? <span class="hljs-literal">true</span> : <span class="hljs-literal">false</span>;
<span class="hljs-comment">// ummm. actually no. we can just remove operator and its required statements and it will still return true or false based on the condition</span>

<span class="hljs-keyword">const</span> compare = <span class="hljs-function">(<span class="hljs-params">a, b</span>) =&gt;</span> (a &gt; b);
<span class="hljs-comment">// we should shorten the code, where there is scope, but yes without messing with the readability of the code</span>
</code></pre>
<h3 id="heading-nullish-coalescing">Nullish Coalescing</h3>
<p>Nullish coalescing is another operator that allows us to handle <code>null</code> or <code>undefined</code> values in a more concise way. The nullish coalescing operator (<code>??</code>) returns the value on its left-hand side if it is not <code>null or undefined</code>, otherwise it returns the value on its right-hand side. The syntax is</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> name = username ?? <span class="hljs-string">"Guest"</span>;
<span class="hljs-comment">// if the user name will ever be NULL or UNDEFINED, then name variable will be assigned the value of GUEST.</span>
</code></pre>
<p>But when is this useful? Whenever we are letting users or an API create an object, then it may be possible that the object ends up having undefined and null in some property. In those scenarios, it will be helpful.</p>
<p>Earlier this work is done by using <code>OR</code> operator <code>||</code> , but one problem with that is if the value is <code>0</code> or a <code>blank string ''</code> then also the default value is get shown. But with <code>??</code> , only Null and Undefined can trigger the default value.</p>
<h3 id="heading-optional-chaining">Optional Chaining</h3>
<p>So if we have to deal with <code>Null</code> or <code>Undefined</code> we get Nullish Coalescing, but what if we want to avoid an error? <code>Null or Undefind</code> is still fine as it can be shown on a rendered page. But an error stops the code processing right away. So for that, we got Optional Chaining. Whenever and specifically the function where we are expecting an error, just after that we include a <code>?</code> and then if the error actually comes, then the function will return just an <code>undefined</code> rather than throwing an error.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> person = {
  <span class="hljs-attr">name</span> : <span class="hljs-string">"example"</span>,
  <span class="hljs-attr">age</span> : <span class="hljs-number">23</span>
}
<span class="hljs-built_in">console</span>.log(person.salary?.()) <span class="hljs-comment">// output : undefined</span>
<span class="hljs-comment">// Here as we can see there is no method (function inside an object) called SALARY.</span>
<span class="hljs-comment">// so if we expected that error, we include a (?) after it. and it outputs undefined.</span>
</code></pre>
<p>But why it is important? because if we get an error, then we can’t do anything at the user end, the code stops and app crashes and the user gets confused. Instead, if we know that this part is coming from some API or somewhere else and for that, it might throw an error, then we take <strong>Optional Chaining (?)</strong> include it in the code and gets an <code>undefined</code>. and guess what, it is much easier (also better) to set a fallback for the undefined than an error.</p>
<h3 id="heading-here-all-of-them-come-together">Here all of them come together</h3>
<p>(: <mark>Finally Justice League &lt;3</mark> : <mark>Dude not again, seriously</mark> : <mark>Oh sorry</mark>)</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> obj = {}
<span class="hljs-keyword">const</span> testFunc = <span class="hljs-function"><span class="hljs-params">obj</span> =&gt;</span> obj.test ? <span class="hljs-literal">true</span> : obj.salary?.() ?? <span class="hljs-string">"test failed"</span>

<span class="hljs-built_in">console</span>.log(testFunc(obj))
<span class="hljs-comment">// Here all the three concepts are used : Ternary Operator, Optional Chaining and Nullish Coalescing in this same order</span>
</code></pre>
<p>And that's it, my friends. I am sure from now on, any one of us won't be confused by this little sign of a question mark. See you in the next blog. Pika said <em>Love Love</em> to you all.</p>
</br><p style="color:#757CF9;">This article is published w/ <a target="_blank" href="https://scattr.io?ref=dev">Scattr  ↗️</a></p>