Enough JavaScript to get you Started : #18 Optional chaining and nullish coalescing

Enough JavaScript to get you Started : #18 Optional chaining and nullish coalescing

Β·

5 min read

Optional Chanining ?.

πŸ‘‰ According to MDN 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.

πŸ‘‰ 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
πŸ‘‰ Unlike manual testing with our code , it won't give us error , rather it returns undefined.


Nullish coalescing ??

πŸ‘‰ According to MDN 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 || πŸ€”?
πŸ‘‰ The answer is yes definitely but this might not work in some falsy values like "" or NaN

πŸ‘‰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(??)

let cartItems = 0;
let msg = "";

let qty = cartItems  ?? 10;
let message = msg ?? "hi!";
console.log(qty);     // 0 βœ”
console.log(message); // "" βœ”

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 :)

Keep Coding ❀

Hey Let's Connect πŸ‘‹
Twitter / GitHub