Consider this Svelte code snippet:
<script>
let count = 1;
$: doubled = count * 2;
</script>
<button on:click={() => count++}>Increment</button>
<p>Doubled value: {doubled}</p>What will be displayed after clicking the button twice?
<script> let count = 1; $: doubled = count * 2; </script> <button on:click={() => count++}>Increment</button> <p>Doubled value: {doubled}</p>
Remember the reactive statement updates whenever count changes.
The variable doubled reacts to changes in count. Starting at 1, after two increments, count becomes 3, so doubled is 3 * 2 = 6. Thus, 'Doubled value: 6' is displayed.
Given this Svelte script:
<script> let a = 2; let b = 3; $: total = a + b; a = 5; </script>
What is the value of total after these statements?
<script> let a = 2; let b = 3; $: total = a + b; a = 5; </script>
Reactive statements run whenever their dependencies change.
Initially, total is 2 + 3 = 5. Then a changes to 5, so total updates to 5 + 3 = 8.
Identify the option that will cause a syntax error when used as a reactive statement in Svelte:
Check the syntax of conditional expressions inside reactive statements.
Option A uses an invalid syntax with 'else' outside a proper conditional block or ternary expression, causing a syntax error.
Consider this Svelte code:
<script>
let items = [];
$: count = items.length;
function addItem() {
items.push('new');
}
</script>
<button on:click={addItem}>Add</button>
<p>Count: {count}</p>Clicking 'Add' does not update the count. Why?
<script> let items = []; $: count = items.length; function addItem() { items.push('new'); } </script> <button on:click={addItem}>Add</button> <p>Count: {count}</p>
Think about how Svelte tracks changes to arrays.
Svelte reactivity tracks assignments, not mutations. Using push mutates the array but does not assign a new value, so reactive statements depending on items do not run.
Given this reactive statement:
$: result = a + b * c;
Which statement best describes when result updates?
Consider how reactive statements track dependencies automatically.
Svelte tracks all variables used in the reactive statement. If any of a, b, or c change, result recalculates.