Consider this Svelte component code:
<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>Clicked {count} times</button>What will the button display after clicking it 3 times?
<script> let count = 0; function increment() { count += 1; } </script> <button on:click={increment}>Clicked {count} times</button>
Think about how the count variable changes on each click and how Svelte updates the DOM.
Each click calls increment which adds 1 to count. After 3 clicks, count is 3, so the button shows "Clicked 3 times".
Which of these Svelte snippets will cause a syntax error when compiled?
Check how event handlers expect functions, not expressions.
Option B uses count++ directly in the event handler, which is an expression, not a function. Svelte expects a function reference or inline function for on:click. This causes a syntax error.
Look at this Svelte code:
<script>
let obj = { value: 0 };
function increment() {
obj.value += 1;
}
</script>
<button on:click={increment}>Value: {obj.value}</button>Clicking the button does not update the displayed value. Why?
<script> let obj = { value: 0 }; function increment() { obj.value += 1; } </script> <button on:click={increment}>Value: {obj.value}</button>
Think about how Svelte tracks changes to variables.
Svelte tracks reactivity by variable assignments. Changing a property inside an object does not change the object reference, so Svelte does not update the UI. To fix, reassign the object: obj = {...obj, value: obj.value + 1}.
Choose the best explanation for why Svelte does not use a virtual DOM.
Think about how Svelte generates code before the app runs.
Svelte compiles your code into small, efficient JavaScript that updates the DOM directly without the overhead of diffing a virtual DOM at runtime. This leads to faster updates and smaller bundles.
Given this Svelte component:
<script>
let count = 1;
$: doubled = count * 2;
function update() {
count = 3;
count = 5;
}
</script>
<button on:click={update}>Count: {count}, Doubled: {doubled}</button>What will the button display after clicking it once?
<script> let count = 1; $: doubled = count * 2; function update() { count = 3; count = 5; } </script> <button on:click={update}>Count: {count}, Doubled: {doubled}</button>
Consider how Svelte processes reactive statements and variable assignments.
The function update sets count to 3, then immediately to 5. Only the last assignment matters. The reactive statement recalculates doubled as 5 * 2 = 10. So the button shows "Count: 5, Doubled: 10".