Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found.
Note: The code is using spread syntax
, not rest parameters
.
const fn1 = undefined
const args = []
const fn2 = () => {}
const fn3 = () => {}
console.log(fn1?.(...args, fn2, fn3))
Error:
console.log(fn1?.(...args, fn2, fn3))
^
TypeError: Function.prototype.apply was called on undefined, which is an undefined and not a function
To enable optional chaining, you need to install a package. At the time of writing, optional chaining is not natively supported in Javascript, it is a new feature introduced in ES2020. Until it is fully adopted we can get all the optional goodness by installing a package!
Optional chaining is a process for querying and calling properties, methods, and subscripts on an optional that might currently be nil . If the optional contains a value, the property, method, or subscript call succeeds; if the optional is nil , the property, method, or subscript call returns nil .
The Difference Between call() and apply() The difference is: The call() method takes arguments separately. The apply() method takes arguments as an array. The apply() method is very handy if you want to use an array instead of an argument list.
apply() The apply() method calls the specified function with a given this value, and arguments provided as an array (or an array-like object).
It turns out to be a V8 bug, I've submitted it there, hopefully, it'll be fixed soon.
Update: it has been fixed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With