Rules Hub
Coding Rules Library
Prefer optional chaining for nested property access
Use the optional chaining operator (?.) to access deeply nested properties instead of verbose logical AND checks.
Bad example
| 1 | const city = response && |
| 2 | response.data && |
| 3 | response.data.user && |
| 4 | response.data.user.address && |
| 5 | response.data.user.address.city; |
Explanation (EN)
Using repeated logical AND (&&) operators to guard against null/undefined values is verbose and repetitive. It creates visual noise and makes the code harder to read and modify.
Objašnjenje (HR)
Korištenje ponovljenih logičkih AND (&&) operatora za provjeru null/undefined vrijednosti je opširno i repetitivno. Stvara vizualni šum i čini kod težim za čitanje i izmjenu.
Good example
| 1 | const city = response?.data?.user?.address?.city; |
Explanation (EN)
Optional chaining (?.) provides a safe and concise way to access nested properties. If any reference in the chain is nullish (null or undefined), the expression short-circuits and returns undefined immediately.
Objašnjenje (HR)
Opcionalno ulančavanje (?.) pruža siguran i sažet način za pristup ugniježđenim svojstvima. Ako je bilo koja referenca u lancu nullish (null ili undefined), izraz se prekida i odmah vraća undefined.