Introduction
Reactive assignments in Svelte automatically update values and the user interface when data changes. This helps keep your app in sync without extra work.
Reactive assignments in Svelte automatically update values and the user interface when data changes. This helps keep your app in sync without extra work.
$: variable = expression;
The $: label marks a reactive assignment.
Whenever any value in the expression changes, the assignment runs again.
doubled that updates when count changes.$: doubled = count * 2;greeting whenever name changes.$: greeting = `Hello, ${name}!`;We start with count as 1 and doubled is 2. Then we change count to 3, so doubled updates to 6 automatically.
let count = 1; $: doubled = count * 2; // Simulate changing count count = 3; console.log(doubled);
Reactive assignments run immediately when the component starts.
They re-run only when the values they depend on change.
Use $: to create reactive assignments in Svelte.
They keep your data and UI in sync automatically.
They help write simpler and cleaner code.
$: symbol before a statement do?$: in Svelte$: prefix marks a statement as reactive, meaning it runs whenever its dependencies change.$: means reactive assignment [OK]$: triggers updates automatically [OK]$: declares constants$: with comments$: imports modules$: followed by the assignment without extra keywords.let with $:. const $total = price * quantity; misuses const and variable naming. total := price * quantity; uses invalid assignment operator.$: variable = value; [OK]$: and assign normally [OK]let or const before $:$let count = 2; $: double = count * 2; count = 5;
double after these lines run?count is 2, so double becomes 4 reactively.count and trigger reactive assignmentcount changes to 5, the reactive line recalculates double = 5 * 2 = 10.double = 10 [OK]double stays at initial valuecount value with doublelet a = 3; $: b = a + c; let c = 4;
c before it is declared, causing an error.const (A), can use variables (B), and semicolons are optional (C).c is used before declaration. -> Option AuserId changes. Which reactive assignment correctly updates userData?$: to reactively assign a promise from fetch when userId changes.await incorrectly outside async context. $: userData = fetch(`/api/user/${userId}`); assigns fetch promise without parsing JSON.$: with fetch and .then() for reactive async [OK]$: with fetch and .then() for reactive async data [OK]$: for reactive updateawait outside async functionPass the test and this pattern moves unknown