55 lines
2.1 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
The optional chaining operator `?.` allows to access a deeply nested property, returning `undefined` if the property or any intermediate object is `undefined`.
This usually means that the expression is expected to evaluate as `undefined` in some cases. Therefore, using the optional chaining operator in a context where returning `undefined` throws an error can lead to runtime exceptions.
[source,javascript]
----
(event?.callback)(); // Noncompliant: when 'event' does not have 'callback' property TypeError is thrown
const { code } = event?.error; // Noncompliant: when 'event' does not have 'error' property TypeError is thrown
func(...event?.values); // Noncompliant: when 'event' does not have 'values' property TypeError is thrown
----
Since optional chaining represents multiple execution branches, having an error thrown in such a context can be hard to debug.
== How to fix it
In order to prevent runtime errors, you should provide fallbacks for when the optional chaining operator short-circuits to `undefined`.
* Nullish coalescing operator `??`
[source,javascript]
----
(event?.callback ?? defaultCallback)();
----
* Logical OR operator `||`
[source,javascript]
----
(event?.callback || defaultCallback)();
----
* Ternary operator `condition ? exprIfTrue : exprIfFalse`
[source,javascript]
----
(event?.callback ? event?.callback : defaultCallback)();
----
//=== How does this work?
//=== Pitfalls
//=== Going the extra mile
== Resources
=== Documentation
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining[Optional chaining (?.)]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Nullish_coalescing[Nullish coalescing operator (??)]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR[Logical OR (||)]
* MDN web docs - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_operator[Conditional (ternary) operator]
//=== Articles & blog posts
//=== Conference presentations
//=== Standards