@babel/plugin-proposal-optional-chaining
Calling deeply nested functions
const obj = {
foo: {
bar: {
baz() {
return 42;
},
},
},
};
const baz = obj?.foo?.bar?.baz(); // 42
const safe = obj?.qux?.baz(); // undefined
const safe2 = obj?.foo.bar.qux?.(); // undefined
const willThrow = obj?.foo.bar.qux(); // Error: not a function
// Top function can be called directly, too.
function test() {
return 42;
}
test?.(); // 42
const obj = {
foo: {
bar: {
baz: class {
},
},
},
};
const baz = new obj?.foo?.bar?.baz(); // baz instance
const safe = new obj?.qux?.baz(); // undefined
const safe2 = new obj?.foo.bar.qux?.(); // undefined
const willThrow = new obj?.foo.bar.qux(); // Error: not a constructor
// Top classes can be called directly, too.
class Test {
}
new Test?.(); // test instance
new exists?.(); // undefined
Deleting deeply nested properties
Added in: v7.8.0
const obj = {
bar: {},
},
};
const ret = delete obj?.foo?.bar?.baz; // true
{
"plugins": ["@babel/plugin-proposal-optional-chaining"]
}
Via CLI
babel --plugins @babel/plugin-proposal-optional-chaining script.js
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-proposal-optional-chaining"],
});
loose
boolean
, defaults to false
.
Example
In
foo?.bar;
foo == null ? void 0 : foo.bar;
Out (noDocumentAll === false
)