Consider this Svelte page code:
<script>
export let name = 'Guest';
</script>
<h1>Hello {name}!
</h1>What will the page show if no name is passed?
<script> export let name = 'Guest'; </script> <h1>Hello {name}!</h1>
Check the default value assigned to name.
The export let name = 'Guest'; line sets a default value 'Guest' if no value is passed. So the page shows 'Hello Guest!'.
Given this Svelte page:
<script>
let count = 0;
function increment() {
count += 1;
}
</script>
<button on:click={increment}>Click me</button>
<p>Clicked {count} times</p>What will the paragraph show after clicking the button twice?
<script> let count = 0; function increment() { count += 1; } </script> <button on:click={increment}>Click me</button> <p>Clicked {count} times</p>
Each click calls increment which adds 1 to count.
Clicking twice calls increment twice, increasing count from 0 to 2. The paragraph updates reactively.
You want to fetch JSON data from /api/data when the page loads and store it in items. Which code snippet is correct?
Think about when the fetch runs and how to handle async in Svelte.
Option A uses onMount to run the fetch after the component mounts, correctly awaiting the response and updating items. Option A runs fetch immediately but does not guarantee component is ready. Option A calls an async function immediately but is less idiomatic. Option A has a syntax error: fetch(...).json() is invalid.
Look at this code:
<script>
export let user = { name: 'Alice' };
function changeName() {
user.name = 'Bob';
}
</script>
<h1>Hello {user.name}!</h1>
<button on:click={changeName}>Change Name</button>Clicking the button does not update the displayed name. Why?
<script> export let user = { name: 'Alice' }; function changeName() { user.name = 'Bob'; } </script> <h1>Hello {user.name}!</h1> <button on:click={changeName}>Change Name</button>
Think about how Svelte tracks changes to variables and objects.
Svelte tracks assignments to variables to update the UI. Changing a property inside an object does not trigger reactivity. You must assign a new object, e.g., user = {...user, name: 'Bob'}, to update the UI.
You have a Svelte page that fetches a list of products. You want to pass this list to a nested <ProductList> component. Which approach correctly passes the data?
Recall how props are passed in Svelte components.
Option B passes the products variable as a prop to ProductList. Option B tries to bind a prop which is for two-way binding and requires the child to declare export let products. Option B is invalid syntax for passing props. Option B is invalid inside component usage.