javascript / intermediate
Snippet
Reactive Declarations for Complex Logic
Svelte's reactive declarations ($:) automatically re-evaluate whenever their dependencies (like 'price' or 'taxRate') change. They can be used to derive state or to trigger side effects (like logging or API calls) in response to state changes without needing manual listeners.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
<script>export let price = 0;export let taxRate = 0.19;$: total = price * (1 + taxRate);$: isExpensive = total > 1000;$: if (isExpensive) {console.warn('High value item detected!');}</script>
svelte
Breakdown
1
$: total = price * (1 + taxRate);
Declares 'total' as a reactive variable that updates whenever price or taxRate changes.
2
$: if (isExpensive) { ... }
A reactive statement used as a side effect, executing logic whenever 'isExpensive' becomes true.