0
0
SvelteHow-ToBeginner · 3 min read

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, where array is your data and item is 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 key when rendering complex lists, which can cause inefficient updates.
  • Trying to loop over a non-iterable value like null or undefined.

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

FeatureDescriptionExample
Basic loopLoops over array items{#each array as item} ... {/each}
With indexAccess item index{#each array as item, i} ... {/each}
With keyUse unique key for updates{#each array as item (item.id)} ... {/each}
Empty listShow 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.