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
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?
Share Improve this question edited Jul 4, 2020 at 9:47 jonrsharpe 122k30 gold badges266 silver badges473 bronze badges asked Jul 4, 2020 at 9:41 Adarsh MadrechaAdarsh Madrecha 7,90612 gold badges76 silver badges127 bronze badges 2 |3 Answers
Reset to default 16const 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.
const {name2} = myObj2 ?? {}
– hgb123 Commented Jul 4, 2020 at 9:54const name2 = myObj2?.name2
, and ifmyObj2?.name2
is an object then you will end up having the same reference which might cause issues by any chance you mutatename2
. – Nithish Commented Jul 4, 2020 at 9:58