Optional Chaining Operator

?.

Status

Stage 1

https://github.com/tc39/proposal-optional-chaining

Sytax

obj?.prop       // optional static property access
obj?.[expr]     // optional dynamic property access
func?.(...args) // optional function or method call

If the operand at the left-hand side of the ?. operator evaluates to undefined or null, the expression evaluates to undefined.

Compare

Subtitle

const a = {
    b: {
    	c: {
            d: 'hi'
        }
    }
};

const hi = a && a.b && a.b.c && a.b.c.d;

// or

const { a: { b: { c: { d: hi } = {} } = {} } = {} } = {};

// or

const hi = a?.b?.c?.d;

When is this better?

Just need one value from deep in an obj.

Credits

https://github.com/tc39/proposal-optional-chaining

Copy of Optional Chaining

By Matthew Poulson

Copy of Optional Chaining

  • 481