Consider this Svelte component code that updates a list immutably. What will be the rendered list after clicking the button once?
<script>
let items = ['apple', 'banana', 'cherry'];
function addItem() {
items = [...items, 'date'];
}
</script>
<button on:click={addItem}>Add Date</button>
<ul>
{#each items as item}
<li>{item}</li>
{/each}
</ul>Think about how the spread operator creates a new array including the old items plus the new one.
The addItem function creates a new array by copying all existing items and adding 'date' at the end. This updates the items variable immutably, so the list renders with the new item included.
Given this Svelte code, what is the value of user after calling updateName()?
<script>
let user = { name: 'Alice', age: 30 };
function updateName() {
user = { ...user, name: 'Bob' };
}
updateName();
</script>Remember the spread operator copies all properties, then the new name replaces the old one.
The spread operator copies all properties from user. Then name: 'Bob' overwrites the name property. So the new object has name as 'Bob' and age unchanged.
Look at this Svelte code snippet. Why does the UI not update after calling updateCount()?
<script>
let state = { count: 0 };
function updateCount() {
state.count += 1;
}
</script>
<button on:click={updateCount}>Increment</button>
<p>{state.count}</p>Think about how Svelte tracks changes to variables by their references.
Svelte tracks changes by variable assignment. Mutating a property inside an object does not change the object reference. So Svelte does not detect the change and does not update the UI. To fix this, assign a new object to state.
Given this state, which code correctly updates the second item in colors immutably?
<script>
let palette = { colors: ['red', 'green', 'blue'] };
function updateGreen() {
// update 'green' to 'lime'
}
</script>Remember to create new arrays and objects instead of mutating existing ones.
Option A creates a new array by slicing and inserting 'lime' immutably, then creates a new object with the updated array. Option A mutates the array directly, so no reactivity. Option A replaces colors but loses other properties if any. Option A uses splice which mutates and returns removed items, causing wrong assignment.
Which statement best explains why immutable updates are crucial for Svelte's reactivity system?
Think about how Svelte knows when to update the UI.
Svelte's reactivity depends on detecting when a variable is assigned a new value. Immutable updates create new object or array references, which Svelte notices and uses to update the UI. Mutating existing objects without reassignment does not trigger updates.