Rules Hub
Coding Rules Library
Prefer const with IIFE over mutable let
Avoid using 'let' for variables that are only reassigned during initialization; use IIFEs or helper functions to keep them 'const'.
Bad example
| 1 | let watchlistId: number | null = null; |
| 2 | let items: Instrument[] = defaultItems; |
| 3 |
|
| 4 | try { |
| 5 | const lists = await fetchWatchlists(); |
| 6 | if (lists.length > 0) { |
| 7 | watchlistId = lists[0].id; |
| 8 | items = await fetchInstruments(watchlistId); |
| 9 | } |
| 10 | } catch (error) { |
| 11 | // Error swallowed, keeping defaults |
| 12 | } |
Explanation (EN)
Using 'let' allows the variable to be mutated anywhere in the scope, making the data flow harder to trace. The logic is fragmented across declaration and initialization.
Objašnjenje (HR)
Korištenje 'let' omogućuje mutaciju varijable bilo gdje u opsegu, što otežava praćenje toka podataka. Logika je fragmentirana između deklaracije i inicijalizacije.
Good example
| 1 | const { watchlistId, items } = await (async () => { |
| 2 | try { |
| 3 | const lists = await fetchWatchlists(); |
| 4 | if (lists.length > 0) { |
| 5 | const id = lists[0].id; |
| 6 | const instruments = await fetchInstruments(id); |
| 7 | return { watchlistId: id, items: instruments }; |
| 8 | } |
| 9 | } catch (error) { |
| 10 | // Ignore error |
| 11 | } |
| 12 | return { watchlistId: null, items: defaultItems }; |
| 13 | })(); |
Explanation (EN)
By using an Immediately Invoked Function Expression (IIFE) or a utility function, we encapsulate the complex logic and return the final value. This allows us to use 'const', ensuring immutability.
Objašnjenje (HR)
Korištenjem IIFE (Immediately Invoked Function Expression) ili pomoćne funkcije, enkapsuliramo složenu logiku i vraćamo konačnu vrijednost. To nam omogućuje korištenje 'const', osiguravajući nepromjenjivost.
Notes (EN)
If your project has a dedicated 'compute' utility (e.g. `const val = compute(() => ...)`), prefer using that over raw IIFEs for better readability.
Bilješke (HR)
Ako vaš projekt ima namjenski 'compute' alat (npr. `const val = compute(() => ...)`), preferirajte ga umjesto čistih IIFE-a radi bolje čitljivosti.