The Optional Chaining Operator allows you to handle properties of deeply nested objects without worrying about undefined intermediate objects.
Example Accessing deeply nested propertiesCalling deeply nested functionsconst obj = {
  foo: {
    bar: {
      baz: 42,
    },
  },
};
Â
const baz = obj?.foo?.bar?.baz;Â
Â
const safe = obj?.qux?.baz;Â
Â
obj?.foo.bar?.baz;Â
                  Â
Constructing deeply nested classesconst obj = {
  foo: {
    bar: {
      baz() {
        return 42;
      },
    },
  },
};
Â
const baz = obj?.foo?.bar?.baz();Â
Â
const safe = obj?.qux?.baz();Â
const safe2 = obj?.foo.bar.qux?.();Â
Â
const willThrow = obj?.foo.bar.qux();Â
Â
function test() {
  return 42;
}
test?.();Â
Â
exists?.();Â
Installationconst obj = {
  foo: {
    bar: {
      baz: class {
      },
    },
  },
};
Â
const baz = new obj?.foo?.bar?.baz();Â
Â
const safe = new obj?.qux?.baz();Â
const safe2 = new obj?.foo.bar.qux?.();Â
Â
const willThrow = new obj?.foo.bar.qux();Â
Â
class Test {
}
new Test?.();Â
Â
new exists?.();Â
Usage Vianpm install --save-dev babel-plugin-transform-optional-chaining
.babelrc
(Recommended)
.babelrc
Via CLI{
  "plugins": ["transform-optional-chaining"]
}
Via Node APIbabel --plugins transform-optional-chaining script.js
Referencesrequire("babel-core").transform("code", {
  plugins: ["transform-optional-chaining"]
});
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4