@babel/plugin-proposal-optional-chaining

    Calling deeply nested functions

    1. const obj = {
    2. foo: {
    3. bar: {
    4. baz() {
    5. return 42;
    6. },
    7. },
    8. },
    9. };
    10. const baz = obj?.foo?.bar?.baz(); // 42
    11. const safe = obj?.qux?.baz(); // undefined
    12. const safe2 = obj?.foo.bar.qux?.(); // undefined
    13. const willThrow = obj?.foo.bar.qux(); // Error: not a function
    14. // Top function can be called directly, too.
    15. function test() {
    16. return 42;
    17. }
    18. test?.(); // 42
    1. const obj = {
    2. foo: {
    3. bar: {
    4. baz: class {
    5. },
    6. },
    7. },
    8. };
    9. const baz = new obj?.foo?.bar?.baz(); // baz instance
    10. const safe = new obj?.qux?.baz(); // undefined
    11. const safe2 = new obj?.foo.bar.qux?.(); // undefined
    12. const willThrow = new obj?.foo.bar.qux(); // Error: not a constructor
    13. // Top classes can be called directly, too.
    14. class Test {
    15. }
    16. new Test?.(); // test instance
    17. new exists?.(); // undefined

    Deleting deeply nested properties

    Added in: v7.8.0

    1. const obj = {
    2. bar: {},
    3. },
    4. };
    5. const ret = delete obj?.foo?.bar?.baz; // true
    1. {
    2. "plugins": ["@babel/plugin-proposal-optional-chaining"]
    3. }

    Via CLI

    1. babel --plugins @babel/plugin-proposal-optional-chaining script.js
    1. require("@babel/core").transformSync("code", {
    2. plugins: ["@babel/plugin-proposal-optional-chaining"],
    3. });

    loose

    boolean, defaults to false.

    Example

    In

    1. foo?.bar;
    1. foo == null ? void 0 : foo.bar;

    Out (noDocumentAll === false)