Search code examples
javascriptobjectecmascript-6destructuring

How to destructure an object by assigning default value when value is already null


The given object value can either of those.

const obj = null
const obj = { param : null}
const obj = { param : {innerParam: 10}}

I want to extract innerParam from param const { param : {innerParam} ={}} =obj but it is throwing error Cannot destructure property 'innerParam' of ''{}'' as it is null. Is there a solution by assigning param to a default object while destructuring.

Note: I need a one liner code. I want avoid doing the below operation

const { param  = {} } =obj;
const { innerParam } = param || {};

Solution

  • const { innerParam } = (obj.param || {});
    

    You still need to check that innerParam is defined. You can also add a default value like this:

    const innerParam = ((obj.param || {}).innerParam) || "default";