How to Use {#each} Block in Svelte: Simple Looping Guide
In Svelte, use the
{#each} block to loop over arrays and render repeated elements. The syntax is {#each array as item} followed by the HTML to repeat, ending with {/each}. This creates a list dynamically based on your data.Syntax
The {#each} block loops over an array or iterable. Inside the block, you define a variable to represent each item. You close the block with {/each}.
Parts explained:
{#each array as item}: Starts the loop, wherearrayis your data anditemis each element.- HTML inside the block: This is repeated for every
item. {/each}: Ends the loop block.
svelte
{#each items as item}
<p>{item}</p>
{/each}Example
This example shows how to display a list of fruits using the {#each} block. Each fruit is shown inside a paragraph.
svelte
<script> let fruits = ['Apple', 'Banana', 'Cherry']; </script> {#each fruits as fruit} <p>{fruit}</p> {/each}
Output
Apple
Banana
Cherry
Common Pitfalls
Common mistakes when using {#each} include:
- Not closing the block with
{/each}, which causes errors. - Forgetting to use a unique
keywhen rendering complex lists, which can cause inefficient updates. - Trying to loop over a non-iterable value like
nullorundefined.
Always ensure your data is an array and consider adding a key for better performance:
svelte
<!-- Wrong: missing {/each} -->
{#each items as item}
<p>{item}</p>
<!-- Right: with {/each} and key -->
{#each items as item (item.id)}
<p>{item.name}</p>
{/each}Quick Reference
| Feature | Description | Example |
|---|---|---|
| Basic loop | Loops over array items | {#each array as item} ... {/each} |
| With index | Access item index | {#each array as item, i} ... {/each} |
| With key | Use unique key for updates | {#each array as item (item.id)} ... {/each} |
| Empty list | Show fallback if empty | {#each array as item} ... {:else} No items {/each} |
Key Takeaways
Use
{#each} to loop over arrays and render repeated elements in Svelte.Always close the loop with
{/each} to avoid errors.Add a unique
key when looping complex lists for efficient updates.You can access the index by adding a second variable:
{#each array as item, i}.Use
{:else} inside {#each} to handle empty arrays gracefully.