-
Notifications
You must be signed in to change notification settings - Fork 176
/
S6582.html
32 lines (31 loc) · 1.37 KB
/
S6582.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<h2>Why is this an issue?</h2>
<p>Optional chaining allows to safely access nested properties or methods of an object without having to check for the existence of each intermediate
property manually. It provides a concise and safe way to access nested properties or methods without having to write complex and error-prone
<code>null</code>/<code>undefined</code> checks.</p>
<p>This rule flags logical operations that can be safely replaced with the <code>?.</code> optional chaining operator.</p>
<h2>How to fix it</h2>
<p>Replace with <code>?.</code> optional chaining the logical expression that checks for <code>null</code>/<code>undefined</code> before accessing the
property of an object, the element of an array, or calling a function.</p>
<h3>Code examples</h3>
<h4>Noncompliant code example</h4>
<pre data-diff-id="1" data-diff-type="noncompliant">
function foo(obj, arr, fn) {
if (obj && obj.value) {}
if (arr && arr[0]) {}
if (fn && fn(42)) {}
}
</pre>
<h4>Compliant solution</h4>
<pre data-diff-id="1" data-diff-type="compliant">
function foo(obj, arr, fn) {
if (obj?.value) {}
if (arr?.[0]) {}
if (fn?.(42)) {}
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li> MDN web docs - <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining">Optional chaining</a>
</li>
</ul>