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?
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
.
You are doing the right thing, but it not destructuring and not really efficient when you want to destructure multiple properties you can do this.
const myObj = {name: 'Abc', email: "test"} const {name,email} = myObj console.log(name, email) // 'Abc' "test" const myObj1 = null const {name1,email1} = myObj1 || {} // or myObj1?? {} console.log(name1,email1) // undefined undefined
You can try ||
const myObj2 = null; const {name2, name3} = myObj2 || {} console.log(name2, name3); const myObj3 = {name4: "name4"}; const {name4, name5} = myObj3 || {} console.log(name4, name5);
Hope this help.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.