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?
Usage with optional chaining We can combine nullish coalescing with the optional chaining to achieve that.
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.
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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With