0 day streak
javascript / beginner
Snippet

Computing Derived Values Using Reactive Declarations

The $: label creates a reactive declaration that automatically recalculates whenever any of its referenced variables change, providing an idiomatic pattern for computed state.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
<script>
let basePrice = 100;
let taxRate = 0.19;
$: taxAmount = basePrice * taxRate;
$: grandTotal = basePrice + taxAmount;
</script>
<button on:click={() => basePrice += 20}>Increase Price</button>
<p>Total: €{grandTotal.toFixed(2)}</p>
svelte
Breakdown
1
$: taxAmount = basePrice * taxRate;
Automatically recalculates the tax whenever basePrice or taxRate updates.
2
$: grandTotal = basePrice + taxAmount;
Computes the final total dynamically from the other reactive values.