Enough JavaScript to get you Started : #18 Optional chaining and nullish coalescing
Tags: javascript, beginners, webdev, 100daysofcode
Published: 2021-01-26 06:52:14

### Optional Chanining `?.`
👉 According to  [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining) The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

👉 To put it more simply , let's take an example where you have to fetch data to client side from the backend, so data come in form of **JSON** `{javaScript object notation}` but sometimes due to error or wrong credentials `null` will be returned...

👉 So to make our code more error proof we've to do something like
```
// ignore next line if you don't know , assume we're fetching data from server
let data = async fetch('https://randomuser.me/api')
let name ="";

// now data may or may not come so we've to check it like 
if(data)
{
   if(data.user !== null)
   {
       if(data.user.name !== "" or data.user.name !== null)
       {
              let name = data.user.name;
       }
   }
}
```
👉 This code is safer but also more verbose. Our data isn’t even that deeply nested; a more complicated object might have many more levels to check.

👉 Using Optional chaining `?.`
```
let data = async fetch('https://randomuser.me/api')

// using optional chaining
let name = data?.user?.name;
```
👉 As we can see optional chaning `(?.)` helps us to write minimal and optimized code. <br>

👉 To make it even more simpler , optional chaining looks that if data has user object or it is null. if it finds user object it goes one level down and check for name whether it's available or not. if it finds user null it won't go one level down which results in `Cannot read property 'user' of undefined`
<br>
👉 Unlike manual testing with our code , it won't give us error , rather it returns undefined.

<hr>

### Nullish coalescing `??`
👉 According to  [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing_operator) the nullish coalescing operator (??) is a logical operator that returns its right-hand side operand when its left-hand side operand is null or undefined, and otherwise returns its left-hand side operand.

👉 in simple words `??` will return right hand side operand if the left hand value is nullish

**Can't we do that with `||` 🤔?** <br>
👉 The answer is yes definitely but this might not work in some falsy values like `""` or `NaN`<br>

👉_a scenario where `||` won't work..._
```
let cartItems = 0;
let msg = "";

let qty = cartItems  || 10;
let message = msg|| "hi!";
console.log(qty);     // 10 and not 0
console.log(message); // "hi!" and not ""
```
👉the values like `""` , `0` , `NaN` are considered to be falsy value, so logically `||` is doing it's job , but not serving our purpose ! hence we need to use Nullish coalescing(`??`)
<br>
```
let cartItems = 0;
let msg = "";

let qty = cartItems  ?? 10;
let message = msg ?? "hi!";
console.log(qty);     // 0 ✔
console.log(message); // "" ✔
```
<p>Let me know in comment section if you have any doubt or feedback. it's always worth to give time to the thriving developer community :) <br>
<br>
Keep Coding ❤
</p>

<br/>
Hey Let's Connect 👋
[Twitter](https://twitter.com/codarsh) / [GitHub](https://github.com/whoadarshpandya)