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;
});

Explanation

$derived(expr) is equivalent to $derived.by(() => expr). The function must be free of side effects.

Further reading

Problem with a question

Svelte · Middle · question 1

Test yourself

Take the Svelte · Middle quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz