Reactive statements let your code automatically update when data changes. This helps keep your app in sync without extra work.
Reactive statements ($:) in Svelte
$: statement_or_assignment;
The $: prefix marks a reactive statement.
It runs whenever any variable it uses changes.
doubled to twice count whenever count changes.$: doubled = count * 2;count updates.$: console.log('Count changed:', count);
$: {
total = price * quantity;
console.log('Total updated:', total);
}This Svelte component shows a button that increases count. The doubled value updates automatically using a reactive statement. The UI updates to show both values.
<script> let count = 0; $: doubled = count * 2; </script> <button on:click={() => count++} aria-label="Increase count">Increase</button> <p>Count: {count}</p> <p>Doubled: {doubled}</p>
Reactive statements run after the component updates the variables they depend on.
You can use reactive statements for calculations, side effects, or logging.
Be careful to avoid infinite loops by not updating a variable inside its own reactive statement without conditions.
Reactive statements automatically run when their data changes.
Use $: before a statement or assignment to make it reactive.
This helps keep your UI and data in sync easily.
Practice
$: symbol do in a Svelte component?Solution
Step 1: Understand the role of
The$:in Svelte$:prefix is used to mark statements as reactive, meaning they automatically re-run when any variable they use changes.Step 2: Compare with other options
Options A, B, and D describe unrelated Svelte features: async imports, props, and scoped styles, which do not use$:.Final Answer:
It marks a statement as reactive, so it runs when its dependencies change. -> Option BQuick Check:
Reactive statement = runs on data change [OK]
- Confusing $: with props declaration
- Thinking $: imports modules
- Assuming $: styles CSS
Solution
Step 1: Identify correct reactive statement syntax
In Svelte, reactive statements start with$:followed by an assignment or expression, e.g.$: total = a + b;.Step 2: Eliminate incorrect options
let $: total = a + b; incorrectly places$:afterlet. reactive total = a + b; uses a non-existent keywordreactive. const $total = a + b; uses$in variable name incorrectly.Final Answer:
$: total = a + b; -> Option DQuick Check:
Reactive statement syntax = $: expression [OK]
- Using let or const with $: reactive statements
- Writing $: inside variable names
- Using non-existent keywords like reactive
let a = 2; let b = 3; $: sum = a + b; // Later in code b = 5;
What is the value of
sum after b changes?Solution
Step 1: Understand reactive statement behavior
The reactive statement$: sum = a + b;runs wheneveraorbchanges. Initially,a=2andb=3, sosum=5.Step 2: Update after changing
Whenbbchanges to 5, the reactive statement re-runs, updatingsum = 2 + 5 = 7. But note the options carefully: 8 is 8, which is 2 + 6, not correct. 7 is 7, which matches calculation.Final Answer:
7 -> Option AQuick Check:
sum updates automatically = 7 [OK]
- Not updating sum after b changes
- Adding wrong numbers
- Confusing initial and updated values
let count = 0; $: count = count + 1;
Solution
Step 1: Analyze reactive statement effect
The statement$: count = count + 1;runs whenevercountchanges. But it changescountitself, causing it to run again immediately, creating an infinite loop.Step 2: Check other options
Syntax error: missing semicolon after count declaration. is incorrect because semicolons are optional in JS. Reactive statements cannot use let variables. is false; reactive statements can use let variables. No error; this code increments count once. is wrong because the increment repeats endlessly.Final Answer:
This causes an infinite loop because count updates itself reactively. -> Option CQuick Check:
Reactive self-update causes infinite loop [OK]
- Ignoring infinite loops from self-updating reactive statements
- Thinking semicolons cause errors
- Believing reactive statements can't use let variables
discountedPrice only when price or discount change, but discount can sometimes be zero or null. Which reactive statement correctly handles this so discountedPrice is price when discount is falsy?Solution
Step 1: Understand the problem with falsy discount
Ifdiscountis zero or null, we wantdiscountedPriceto equalprice(no discount). A simple calculation without check will give wrong results.Step 2: Evaluate each option
$: discountedPrice = price - (price * discount); always subtractsprice * discount, so zero discount works but null may cause NaN. $: discountedPrice = discount ? price - (price * discount) : price; uses a conditional to check if discount is truthy, else returns price, correctly handling zero and null. $: discountedPrice = price - (price * (discount || 1)); usesdiscount || 1, which makes discount 1 if falsy, causing full price discount (wrong). $: discountedPrice = price * discount || price; multiplies price by discount or price, which gives wrong results when discount is zero.Final Answer:
$: discountedPrice = discount ? price - (price * discount) : price; -> Option AQuick Check:
Use conditional to handle falsy discount [OK]
- Ignoring falsy discount causing wrong calculations
- Using || 1 which changes discount incorrectly
- Assuming zero discount subtracts correctly without check
Ready to prove it?
Pass the test and this pattern moves unknown
