📖 Scenario: You are building a simple Svelte app that tracks the number of items in a shopping cart and updates the total price reactively.
🎯 Goal: Create a Svelte component that uses reactive assignments to update the total price whenever the quantity or price of items changes.
📋 What You'll Learn
Create a variable quantity initialized to 2
Create a variable pricePerItem initialized to 50
Create a reactive assignment for totalPrice that multiplies quantity and pricePerItem
Add a reactive assignment that updates discountedPrice by subtracting 10 from totalPrice
💡 Why This Matters
🌍 Real World
Reactive assignments in Svelte are used to build interactive web apps where UI updates automatically when data changes, such as shopping carts, dashboards, or forms.
💼 Career
Understanding reactive assignments is essential for frontend developers working with Svelte to create efficient and responsive user interfaces.
Progress0 / 4 steps
1
Set up initial variables
Create two variables in your Svelte component: quantity set to 2 and pricePerItem set to 50.
Svelte
Hint
Use let to declare variables in Svelte.
2
Add reactive assignment for totalPrice
Add a reactive assignment for totalPrice that calculates the product of quantity and pricePerItem using $: syntax.
Svelte
Hint
Use $: totalPrice = quantity * pricePerItem; to create a reactive assignment.
3
Add reactive assignment for discountedPrice
Add another reactive assignment for discountedPrice that subtracts 10 from totalPrice using $: syntax.
Svelte
Hint
Use $: discountedPrice = totalPrice - 10; to create the reactive discounted price.
4
Complete the Svelte component with markup
Add markup to display quantity, pricePerItem, totalPrice, and discountedPrice inside <p> tags in your Svelte component.
Svelte
Hint
Use curly braces {} to insert variables inside HTML tags in Svelte.
Practice
(1/5)
1. In Svelte, what does the $: symbol before a statement do?
easy
A. It comments out the line.
B. It makes the statement reactive, updating when dependencies change.
C. It declares a variable as constant.
D. It imports a module.
Solution
Step 1: Understand the role of $: in Svelte
The $: prefix marks a statement as reactive, meaning it runs whenever its dependencies change.
Step 2: Compare with other options
Options A, B, and D describe unrelated concepts: comments (A), constants (B), and imports (D).
Final Answer:
It makes the statement reactive, updating when dependencies change. -> Option B