Consider this Svelte code snippet:
<script>
let fruits = ['apple', 'banana', 'cherry'];
</script>
<ul>
{#each fruits as fruit, i}
<li>{i + 1}: {fruit}</li>
{/each}
</ul>What will be the HTML output inside the <ul>?
<script> let fruits = ['apple', 'banana', 'cherry']; </script> <ul> {#each fruits as fruit, i} <li>{i + 1}: {fruit}</li> {/each} </ul>
Remember that the index i starts at 0, so adding 1 adjusts it to start at 1.
The {#each} block loops over the fruits array. The second variable i is the zero-based index. Adding 1 to i makes the list start counting from 1.
In Svelte, when rendering a list, you can provide a key to help with efficient updates.
Which of the following code snippets correctly uses a key with the {#each} block?
The key is placed in parentheses immediately after the as item part.
The correct syntax for keys in Svelte's {#each} block is {#each items as item (item.id)}. This helps Svelte track items efficiently.
Look at this Svelte code:
<script>
let numbers = null;
</script>
<ul>
{#each numbers as n}
<li>{n}</li>
{/each}
</ul>What error will this code cause when run?
<script> let numbers = null; </script> <ul> {#each numbers as n} <li>{n}</li> {/each} </ul>
The {#each} block expects an array or iterable. What happens if it gets null?
Since numbers is null, it is not iterable. The {#each} block tries to loop over it and throws a TypeError.
Consider this Svelte component:
<script>
let items = ['a', 'b'];
function addItem() {
items = [...items, 'c'];
}
</script>
<ul>
{#each items as item}
<li>{item}</li>
{/each}
</ul>
<button on:click={addItem}>Add</button>What will the list show after clicking the button once?
<script> let items = ['a', 'b']; function addItem() { items = [...items, 'c']; } </script> <ul> {#each items as item} <li>{item}</li> {/each} </ul> <button on:click={addItem}>Add</button>
Think about how the array changes when you add 'c' and how Svelte updates the list.
The addItem function creates a new array with 'c' added at the end. The {#each} block rerenders showing 'a', 'b', and 'c'.
When rendering lists with {#each} in Svelte, you can provide a key for each item.
What is the main reason to use keys in {#each} blocks?
Think about how Svelte updates the DOM when list items change.
Keys help Svelte identify which items changed, were added, or removed. This allows efficient updates without re-rendering the entire list.