javascriptdestructuringoptional-chainingnullish-coalescing

Safe destructuring using nullish coalescing or optional chaining


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?


Solution

  • 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.