Search code examples
javascriptobjectecmascript-6

How to destructure nested object with null value using default value


When trying to destructure a nested object which could be null, the default value is not being used.

I have accomplished this by destructuring in multiple stages, but would rather do it in a single stage if possible.

const obj = { a: null };
const { a: { b, c } = {} } = obj;

This results in error:
Cannot destructure property 'b' of 'undefined' or 'null'

I would expect b and c to be undefined


Solution

  • For the default value to be used, the value which you are destructuring must be undefined.

    const obj = { a: undefined };
    const { a: { b, c } = {} } = obj;
    
    console.log(b, c)