最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Safe destructuring using nullish coalescing or optional chaining - Stack Overflow

programmeradmin1浏览0评论

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
  • 1 try this: const {name2} = myObj2 ?? {} – hgb123 Commented Jul 4, 2020 at 9: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 Commented Jul 4, 2020 at 9:58
Add a comment  | 

3 Answers 3

Reset to default 16

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.

发布评论

评论列表(0)

  1. 暂无评论