Search code examples
javascriptconditional-operatordeconstructor

How do you mix the conditional operator ( ? : ) and deconstructed function returns?


I have a function in a CLASS

MyClass.prototype.fn = function(){
    /* ... some impressive code */
    return {isA: value1, isB: value2};
}

All that is important is it returns an object {isA: ?, isB: ?} ready for deconstructing.

Later I will have an instance of my class:

MyClass myC;

However, when I use it there is a chance the MyClass object myC is null.

So I want to use the conditional operator, just in case myC is null.

My question is, is there a better way of getting the default than just creating a temporary object on the fly with isA and isB set to false?

Ie, is this the best way to do it?

let {isA, isB} = myC ? myC.fn() : {isA: false, isB: false};

Solution

  • Yes, you can set the defaults in the destructuring itself and then fall back to an empty object on the right side:

    let { isA = false, isB = false } = myC?.fn() ?? {}
    

    This way, you dedupe the property names and have one neat source of truth.

    This even works for nested properties, like this:

    const { x = 123, y: { z = 456 } = {} } = { x: 111, y: { z: 222 } }
    console.log(x, z) // 111, 222
    
    const { x = 123, y: { z = 456 } = {} } = {}
    console.log(x, z) // 123, 456
    

    This would provide defaults for all the properties and therefore would also work with partial inputs such as { x: 111 } or { x: 111, y: {} }.