8

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?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Adarsh Madrecha
  • 6,364
  • 11
  • 69
  • 117
  • 1
    try this: `const {name2} = myObj2 ?? {}` – hgb123 Jul 04 '20 at 09:54
  • If you use `const name2 = myObj2?.name2`, and if `myObj2?.name2` is an object then you will end up having the same reference which might cause issues by any chance you mutate `name2`. – Nithish Jul 04 '20 at 09:58

3 Answers3

12

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.

Yousaf
  • 27,861
  • 6
  • 44
  • 69
1

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
Tony Nguyen
  • 3,298
  • 11
  • 19
0

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.

turivishal
  • 34,368
  • 7
  • 36
  • 59