Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Safe destructuring using nullish coalescing or optional chaining

Currently I am using below code for destructuring:

const myObj1 = {name: 'Abc'}
const {name} = myObj1
console.log(name)
const myObj2 = null
const {name2} = myObj2  // this will give error

Now, since we have optional chaining, I can do this:

const myObj = {name: 'Abc'}
const {name} = myObj
console.log(name) // 'Abc'
const myObj2 = null
const name2 = myObj2?.myObj2
console.log(name2) // undefined

Is there a better way or safe method to destructure using nullish coalescing or optional chaining?

like image 652
Adarsh Madrecha Avatar asked Jul 04 '20 09:07

Adarsh Madrecha


People also ask

Can we combine optional chaining and Nullish coalescing?

Usage with optional chaining We can combine nullish coalescing with the optional chaining to achieve that.

Could you explain about optional chaining and Nullish coalescing operator?

The nullish coalescing operator may be used after optional chaining in order to build a default value when no value is found. Generally, accessing values from deeply nested objects in JavaScript can be error-prone because some values might not exist, so they'll evaluate as null or undefined.

What is Nullish coalescing?

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.

What are the advantages of using Destructuring?

There are two big advantages of using destructuring. The first one is that your code more readable. If you destructure an object at the top of a function or code block, it is clear to the reader what variables you are going to use. The second plus is performance.


1 Answers

const name2 = myObj2?.myObj2 - this is NOT destructuring.

myObj2?.myObj2 will return undefined which you are assigning to name2.

You can simply do

const myObj2 = null;
const { name2 } = { ...myObj2 };
console.log(name2); // undefined

If you want to use nullish coalescing operator, then you should use it as shown below:

const myObj2 = null
const {name2} =  myObj2 ?? {};
console.log(name2) // undefined

nullish coalescing operator will return the operand on the right side if myObj2 is null or undefined, otherwise it will return the operand on the left side, which in your case is myObj2.

like image 140
Yousaf Avatar answered Nov 05 '22 06:11

Yousaf