0
0
Svelteframework~30 mins

Derived values with $: in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Derived Values with $ in Svelte
📖 Scenario: You are building a simple Svelte app to track the prices of fruits in a basket and calculate the total cost automatically.
🎯 Goal: Create a Svelte component that holds fruit prices, sets a discount rate, calculates the discounted prices using a derived value with $:, and displays the final total cost.
📋 What You'll Learn
Create a dictionary called prices with exact fruit-price pairs
Add a variable called discount with a decimal value for discount rate
Use a derived value with $: named discountedPrices to calculate prices after discount
Use another derived value with $: named total to sum all discounted prices
Display the discounted prices and total cost in the component
💡 Why This Matters
🌍 Real World
Calculating prices with discounts is common in shopping apps and e-commerce websites to show customers updated costs.
💼 Career
Understanding reactive derived values is essential for building dynamic user interfaces in Svelte, a popular modern frontend framework.
Progress0 / 4 steps
1
Set up the fruit prices dictionary
Create a dictionary called prices with these exact entries: apple: 1.2, banana: 0.8, cherry: 2.5.
Svelte
Need a hint?

Use let prices = { apple: 1.2, banana: 0.8, cherry: 2.5 }; to create the dictionary.

2
Add a discount rate variable
Add a variable called discount and set it to 0.1 to represent a 10% discount.
Svelte
Need a hint?

Use let discount = 0.1; to set the discount rate.

3
Create derived value for discounted prices
Use a derived value with $: named discountedPrices that creates a new dictionary by multiplying each price in prices by (1 - discount).
Svelte
Need a hint?

Use $: discountedPrices = { apple: prices.apple * (1 - discount), ... } to create the derived dictionary.

4
Create derived value for total and display results
Use a derived value with $: named total that sums all values in discountedPrices. Then add HTML to display each discounted price and the total cost inside <main> tags.
Svelte
Need a hint?

Use $: total = discountedPrices.apple + discountedPrices.banana + discountedPrices.cherry; and add HTML inside <main> to show prices and total.