📖 Scenario: You are building a simple Svelte component that calculates the total price of items in a shopping cart. The prices and quantities can change, and the total should update automatically.
🎯 Goal: Create a Svelte component that uses reactive statements ($:) to automatically update the total price when the quantity or price changes.
📋 What You'll Learn
Create variables for item price and quantity
Create a reactive statement using $: to calculate the total price
Display the price, quantity, and total price in the component
Update the total price automatically when price or quantity changes
💡 Why This Matters
🌍 Real World
Reactive statements are useful in real apps to keep UI and data in sync automatically, like updating totals, filtering lists, or calculating values.
💼 Career
Understanding reactive statements is key for Svelte developers to build efficient, responsive user interfaces that update smoothly without manual event handling.
Progress0 / 4 steps
1
Set up price and quantity variables
Create two variables in the <script> block: price set to 10 and quantity set to 2.
Svelte
Hint
Use let to declare variables inside the <script> block.
2
Add a reactive statement for total price
Add a reactive statement using $: to create a variable total that calculates price * quantity.
Svelte
Hint
Use $: total = price * quantity; to create a reactive statement that updates total automatically.
3
Display the total price in the component
Replace the comment inside the <p> tag for total with {total} to show the calculated total price.
Svelte
Hint
Use curly braces {total} inside the HTML to display the reactive variable.
4
Make price and quantity editable with inputs
Add two <input> elements with type="number" and bind their values to price and quantity using bind:value. Place them above the paragraphs.
Svelte
Hint
Use <input type="number" bind:value={price} /> and similarly for quantity to make them editable.
Practice
(1/5)
1. What does the $: symbol do in a Svelte component?
easy
A. It imports a module asynchronously.
B. It marks a statement as reactive, so it runs when its dependencies change.
C. It declares a variable as a prop to the component.
D. It defines a CSS style block scoped to the component.
Solution
Step 1: Understand the role of $: in Svelte
The $: 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 B
Quick Check:
Reactive statement = runs on data change [OK]
Hint: Remember $: means 'run this when data changes' [OK]
Common Mistakes:
Confusing $: with props declaration
Thinking $: imports modules
Assuming $: styles CSS
2. Which of the following is the correct syntax to create a reactive statement in Svelte?
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 $: after let. reactive total = a + b; uses a non-existent keyword reactive. const $total = a + b; uses $ in variable name incorrectly.
Final Answer:
$: total = a + b; -> Option D
Quick Check:
Reactive statement syntax = $: expression [OK]
Hint: Start reactive lines with $: and no let/const [OK]
Common Mistakes:
Using let or const with $: reactive statements
Writing $: inside variable names
Using non-existent keywords like reactive
3. Consider this Svelte code:
let a = 2;
let b = 3;
$: sum = a + b;
// Later in code
b = 5;
What is the value of sum after b changes?
medium
A. 7
B. 5
C. 8
D. 3
Solution
Step 1: Understand reactive statement behavior
The reactive statement $: sum = a + b; runs whenever a or b changes. Initially, a=2 and b=3, so sum=5.
Step 2: Update after changing b
When b changes to 5, the reactive statement re-runs, updating sum = 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 A
Quick Check:
sum updates automatically = 7 [OK]
Hint: Reactive sums update immediately when inputs change [OK]
Common Mistakes:
Not updating sum after b changes
Adding wrong numbers
Confusing initial and updated values
4. Identify the error in this Svelte reactive statement:
let count = 0;
$: count = count + 1;
medium
A. Reactive statements cannot use let variables.
B. Syntax error: missing semicolon after count declaration.
C. This causes an infinite loop because count updates itself reactively.
D. No error; this code increments count once.
Solution
Step 1: Analyze reactive statement effect
The statement $: count = count + 1; runs whenever count changes. But it changes count itself, 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 C
Quick Check:
Reactive self-update causes infinite loop [OK]
Hint: Avoid reactive statements that update their own dependencies [OK]
Common Mistakes:
Ignoring infinite loops from self-updating reactive statements
Thinking semicolons cause errors
Believing reactive statements can't use let variables
5. You want to create a reactive statement that updates 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?
D. $: discountedPrice = price * discount || price;
Solution
Step 1: Understand the problem with falsy discount
If discount is zero or null, we want discountedPrice to equal price (no discount). A simple calculation without check will give wrong results.
Step 2: Evaluate each option
$: discountedPrice = price - (price * discount); always subtracts price * 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)); uses discount || 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.