Performance: Derived values with $:
This affects how efficiently the UI updates when reactive data changes, impacting interaction responsiveness and rendering speed.
let count = 0; $: doubled = count * 2; // reactive declaration function increment() { count += 1; }
let count = 0; let doubled; function increment() { count += 1; doubled = count * 2; // manual update }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Manual updates of derived values | Multiple updates per change | Multiple reflows | Higher paint cost | [X] Bad |
| Using $: reactive declarations | Minimal updates, batched | Single reflow per change | Lower paint cost | [OK] Good |
$: label do in Svelte?$: in Svelte$: label marks a reactive statement that runs whenever its dependencies change.$: means auto-update when data changes [OK]$: declares constants$: with imports or functionsdouble from count in Svelte?$: followed by an assignment. So $: double = count * 2; is correct.let $double = count * 2; wrongly uses let $double, which is invalid. const double = $: count * 2; misplaces $:. double = $count * 2; uses $count which is incorrect syntax.$: double = count * 2; [OK]$: followed by assignment [OK]$ inside variable names$: after the variablelet count = 3; $: double = count * 2; count = 5;
double after count changes?count is 3, so double is 6. When count changes to 5, the reactive statement recalculates double as 5 * 2 = 10.doubledouble is 10, reflecting the latest count.double stays at initial valuelet a = 2; $: b = a + 3 $: c = b * 2;
b.let and updated reactively. No need for const here.status that shows "High" if score is above 80, "Medium" if between 50 and 80, and "Low" otherwise. Which Svelte code correctly implements this?$: status = score > 80 ? 'High' : score >= 50 ? 'Medium' : 'Low'; uses a single reactive assignment with nested ternary operators, which is valid and concise.let status = $: score > 80 ? 'High' : score >= 50 ? 'Medium' : 'Low'; incorrectly combines let and $:. if (score > 80) { status = 'High'; } else if (score >= 50) { status = 'Medium'; } else { status = 'Low'; } uses an if-else block but lacks $: label for reactivity. $: status = (score > 80 && 'High') || (score > 80 && 'Medium') || 'Low'; uses logical operators with duplicate conditions that never produce 'Medium'.$: status = score > 80 ? 'High' : score >= 50 ? 'Medium' : 'Low'; [OK]$: for concise reactive logic [OK]$: for reactive statementslet with $: incorrectlyPass the test and this pattern moves unknown