Svelte · Middle · Question 1 of 75
When should you use $derived.by instead of $derived?
let total = $derived.by(() => {
let sum = 0;
for (const item of cart) sum += item.price * item.qty;
return sum;
});- ✓Correct answer: When the computation needs several statements;
$derivedtakes a single expression - 2When the value must be computed on the server
- 3When the value is a promise
Explanation
$derived(expr) is equivalent to $derived.by(() => expr). The function must be free of side effects.