Rules Hub
Coding Rules Library
Rule priority, scope & exceptions
Use this to align rules with the senior-level structure (P0/P1/P2, scope, exceptions/tradeoffs).
Add object keys conditionally with undefined or a single conditional spread, not `: {}`
To include a key only sometimes, use a ternary returning undefined or a single conditional spread, rather than spreading an empty object in the else branch.
Bad example
| 1 | const config = { |
| 2 | mode: 'production', |
| 3 | ...(isBuild ? { base: `${BASE_URL}/` } : {}), |
| 4 | }; |
Explanation (EN)
Spreading `{}` in the false branch is ceremony: you build and spread an empty object just to add nothing. The reader has to parse the empty-object spread to realize it is a no-op.
Objašnjenje (HR)
Spread praznog objekta `{}` u false grani je suvisna ceremonija: gradis i siris prazan objekt samo da ne dodas nista. Citatelj mora rasclaniti spread praznog objekta da shvati da je rijec o no-op operaciji.
Good example
| 1 | const config = { |
| 2 | mode: 'production', |
| 3 | base: isBuild ? `${BASE_URL}/` : undefined, |
| 4 | }; |
| 5 | // or, for a single conditional key: |
| 6 | const config2 = { |
| 7 | mode: 'production', |
| 8 | ...(isBuild && { base: `${BASE_URL}/` }), |
| 9 | }; |
Explanation (EN)
An `undefined` value is treated the same as an absent key during serialization and by most consumers, so the ternary reads cleanly. A single conditional spread (`&&`) is also fine because a falsy value spreads like `{}`.
Objašnjenje (HR)
Vrijednost `undefined` se prilikom serijalizacije i od strane vecine potrosaca tretira jednako kao da kljuca nema, pa se ternar cita jasno. Jedan uvjetni spread (`&&`) je takoder u redu jer se falsy vrijednost siri kao `{}`.
Notes (EN)
Be aware that an explicit `undefined` value is NOT identical to an absent key for `Object.keys`, `in`, or `hasOwnProperty` checks. When that distinction matters, prefer the conditional-spread form.
Bilješke (HR)
Imaj na umu da eksplicitna `undefined` vrijednost NIJE identicna nepostojecem kljucu za provjere poput `Object.keys`, `in` ili `hasOwnProperty`. Kad je ta razlika bitna, koristi oblik s uvjetnim spreadom.
Exceptions / Tradeoffs (EN)
Balance against prefer-explicit-null-over-conditional-spreads: omit a key (undefined/conditional spread) when consumers and serialization treat 'absent' as correct.