Consider this Svelte code snippet:
let count = 0;
$: doubled = count * 2;
function increment() {
count += 1;
}What is the value of doubled after calling increment() twice?
let count = 0; $: doubled = count * 2; function increment() { count += 1; } increment(); increment(); // What is doubled now?
Reactive blocks run whenever their dependencies change.
Each call to increment() increases count by 1. After two calls, count is 2. The reactive block recalculates doubled as count * 2, so doubled becomes 4.
Given this Svelte code:
let a = 1; let b = 2; $: sum = a + b;
Which action will cause the reactive block to run?
let a = 1; let b = 2; $: sum = a + b; // Which of these triggers the reactive block? // 1) a = 3; // 2) b = 5; // 3) sum = 10; // 4) console.log(sum);
Reactive blocks run when their dependencies change.
The reactive block depends on a and b. Changing either triggers it. Assigning sum directly or logging it does not trigger the block.
What is wrong with this Svelte reactive block?
let x = 5; $: y = x * 2 $: z = y + 3;
let x = 5; $: y = x * 2 $: z = y + 3;
Check if semicolons are mandatory in Svelte reactive blocks.
Svelte reactive blocks do not require semicolons. Multiple reactive statements can be declared consecutively. Curly braces are not needed.
Consider this Svelte code:
let items = [1, 2, 3];
$: total = items.reduce((a, b) => a + b, 0);
function addItem(num) {
items.push(num);
}After calling addItem(4), why does total not update?
let items = [1, 2, 3]; $: total = items.reduce((a, b) => a + b, 0); function addItem(num) { items.push(num); } addItem(4); // What is total now?
Think about how Svelte tracks changes in arrays.
Svelte tracks assignments to variables. Mutating an array with push does not trigger reactivity. Assigning a new array (e.g., items = [...items, num]) would update total.
Given this Svelte code:
let a = 1; $: a = a + 1;
What happens when this code runs, and how can you fix it?
let a = 1; $: a = a + 1;
Think about what triggers reactive blocks and what happens when they update their own dependencies.
The reactive block changes 'a', which triggers the block again, causing an infinite loop. To fix, avoid assigning to 'a' inside a reactive block that depends on 'a'.