Consider this Svelte component with an inline click event handler:
<script>
let count = 0;
</script>
<button on:click={() => count += 1}>Click me</button>
<p>Count: {count}</p>What will the displayed count be after clicking the button 3 times?
<script> let count = 0; </script> <button on:click={() => count += 1}>Click me</button> <p>Count: {count}</p>
Think about how the inline arrow function updates the count variable each time the button is clicked.
The inline event handler increments the count variable by 1 on each click. After 3 clicks, count becomes 3, so the displayed text is Count: 3.
Which of the following inline event handlers in Svelte is syntactically correct for a button click?
Remember that in Svelte, event handlers expect a function reference, not the result of calling the function.
Option A passes the function handleClick as a reference, which is correct. Option A calls the function immediately, which is incorrect syntax for inline handlers. Options C and D are invalid syntax.
Given this Svelte code snippet:
<script>
let message = 'Hello';
</script>
<button on:click={() => message.toUpperCase() }>Click</button>
<p>{message}</p>Why does the displayed message not change after clicking the button?
<script> let message = 'Hello'; </script> <button on:click={() => message.toUpperCase() }>Click</button> <p>{message}</p>
Consider whether the message variable is reassigned inside the event handler.
The toUpperCase() method returns a new string but does not modify the original message variable. Since message is not reassigned, Svelte does not detect a change and the UI stays the same.
Analyze this Svelte component:
<script>
let count = 0;
</script>
<button on:click={() => count++}>Increment</button>
<button on:click={() => count = 0}>Reset</button>
<p>Count: {count}</p>If the user clicks Increment twice, then Reset once, then Increment once, what is the displayed count?
<script> let count = 0; </script> <button on:click={() => count++}>Increment</button> <button on:click={() => count = 0}>Reset</button> <p>Count: {count}</p>
Track each click and how it changes the count variable.
Clicks: Increment (count=1), Increment (count=2), Reset (count=0), Increment (count=1). Final count is 1.
In Svelte, you want to prevent the default form submission when clicking a submit button using an inline event handler. Which option correctly does this?
<form on:submit|preventDefault={handleSubmit}>
<button type="submit">Submit</button>
</form>Recall how Svelte modifiers like |preventDefault are used inline.
Option D uses the Svelte event modifier |preventDefault correctly on the inline event handler. Option D prevents default only on click but does not call handleSubmit. Option D has invalid syntax. Option D does not prevent default behavior.