Consider the following Svelte component that uses a keyed each block to render a list of items. What will be the rendered output after clicking the button once?
<script>
let items = [{ id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }];
function update() {
items = [{ id: 2, name: 'Banana' }, { id: 1, name: 'Apple' }];
}
</script>
<button on:click={update}>Swap Items</button>
<ul>
{#each items as item (item.id)}
<li>{item.name}</li>
{/each}
</ul>Remember that keyed each blocks track items by their key and reorder DOM elements instead of recreating them.
The keyed each block uses item.id as the key. When the list order changes, Svelte reorders the existing DOM nodes instead of recreating them. So the output reflects the swapped order: Banana first, then Apple.
Given the following Svelte code, what will be the value of items after clicking the 'Remove Banana' button?
<script>
let items = [{ id: 1, name: 'Apple' }, { id: 2, name: 'Banana' }, { id: 3, name: 'Cherry' }];
function removeBanana() {
items = items.filter(item => item.id !== 2);
}
</script>
<button on:click={removeBanana}>Remove Banana</button>
<ul>
{#each items as item (item.id)}
<li>{item.name}</li>
{/each}
</ul>Filtering removes the item with id === 2.
The removeBanana function filters out the item with id 2. So the resulting array contains only Apple and Cherry.
Identify the correct syntax for a keyed each block that iterates over users array keyed by user.id.
The key expression goes in parentheses immediately after the as clause.
The correct syntax is {#each users as user (user.id)}. Other options have invalid syntax and will cause errors.
Examine the code below. Why does it cause a runtime error when rendering?
<script>
let items = [{ id: 1, name: 'A' }, { id: 2, name: 'B' }];
</script>
<ul>
{#each items as item (item.key)}
<li>{item.name}</li>
{/each}
</ul>Check the property used as the key in the each block.
The code uses item.key as the key, but the objects have no key property. This causes a runtime error because keys must be defined and unique.
Choose the best explanation of how Svelte uses keys in each blocks to optimize rendering.
Think about how keys help identify items uniquely during list changes.
Keys allow Svelte to match items between renders, so it can reorder or update DOM nodes efficiently without full re-creation.