Derived values with $: let you automatically update one value when others change. It keeps your code simple and reactive without extra work.
0
0
Derived values with $: in Svelte
Introduction
You want to show a total price that updates when quantity or price changes.
You need to format a date string whenever the date value changes.
You want to calculate a user's full name from first and last names.
You want to update a message based on user input instantly.
Syntax
Svelte
$: derivedValue = expression;
The $: label tells Svelte to recalculate derivedValue whenever any variable in expression changes.
You can use multiple $: statements in one component.
Examples
Calculate
total whenever price or quantity changes.Svelte
$: total = price * quantity;
Combine first and last names into
fullName automatically.Svelte
$: fullName = firstName + ' ' + lastName;Create a greeting message that updates when
name changes.Svelte
$: greeting = `Hello, ${name}!`;Sample Program
This Svelte component shows price and quantity. The total updates automatically when quantity changes. Clicking the button increases quantity and updates total instantly.
Svelte
<script> let price = 10; let quantity = 2; $: total = price * quantity; function increaseQuantity() { quantity += 1; } </script> <main> <p>Price: {price} USD</p> <p>Quantity: {quantity}</p> <p><strong>Total: {total} USD</strong></p> <button on:click={increaseQuantity} aria-label="Increase quantity">Add one more</button> </main>
OutputSuccess
Important Notes
Derived values run automatically and efficiently only when needed.
Don't assign to a derived value inside the $: block; it should be computed from other variables.
Summary
$: creates reactive derived values that update automatically.
Use it to keep related data in sync without manual updates.
It makes your Svelte code cleaner and easier to read.