Consider this Svelte component code:
<script>
let count = 1;
$: double = count * 2;
</script>
<button on:click={() => count++}>Increment</button>
<p>Double: {double}</p>What will be shown in the paragraph after clicking the button 3 times?
<script> let count = 1; $: double = count * 2; </script> <button on:click={() => count++}>Increment</button> <p>Double: {double}</p>
Remember that $: runs whenever count changes.
Starting from count = 1, clicking 3 times increments it to 4. The reactive declaration double = count * 2 updates to 8.
sum after this code runs?Given this Svelte script:
<script>
let a = 2;
let b = 3;
$: sum = a + b;
a = 5;
</script>What is the final value of sum?
<script> let a = 2; let b = 3; $: sum = a + b; a = 5; </script>
Reactive declarations update when their dependencies change.
Initially, sum = 2 + 3 = 5. Then a changes to 5, so sum updates to 5 + 3 = 8.
let in Svelte?Choose the valid syntax for a reactive declaration that updates total when x or y change.
Reactive declarations use $: before the statement without let.
In Svelte, reactive declarations do not use let inside the reactive statement. The variable must be declared separately.
Look at this Svelte code:
<script>
let count = 0;
$: double = count * 2;
function increment() {
count += 1;
double = count * 3;
}
</script>
<button on:click={increment}>Click</button>
<p>Double: {double}</p>Why does the paragraph show double as count * 2 instead of count * 3 after clicking?
<script> let count = 0; $: double = count * 2; function increment() { count += 1; double = count * 3; } </script> <button on:click={increment}>Click</button> <p>Double: {double}</p>
Think about how reactive declarations run after any change.
The reactive declaration $: double = count * 2; runs after count changes, overwriting the manual assignment double = count * 3; inside increment.
Consider this code snippet:
<script>
let a = 1;
$: a = a + 1;
</script>What will happen when this component runs?
<script> let a = 1; $: a = a + 1; </script>
Think about what happens when a reactive statement changes the variable it depends on.
The reactive declaration updates a by adding 1, which triggers itself again, causing an infinite loop.