Discover how a tiny loop can save you hours of tedious work and bugs!
Why Each blocks ({#each}) in Svelte? - Purpose & Use Cases
Imagine you have a list of 10 items and you want to show them all on a webpage. You write HTML for each item by hand, and every time the list changes, you have to update the HTML manually.
Manually updating each item is slow and easy to mess up. If the list grows or changes often, you waste time rewriting code and risk forgetting to update some parts, causing bugs or inconsistent displays.
Svelte's {#each} block lets you write one simple loop that automatically creates HTML for every item in your list. When the list changes, Svelte updates the page for you, saving time and avoiding mistakes.
<ul>\n <li>Item 1</li>\n <li>Item 2</li>\n <li>Item 3</li>\n</ul>
<ul>\n {#each items as item}\n <li>{item}</li>\n {/each}\n</ul>You can easily display and update lists of any size with clean, simple code that stays correct as your data changes.
Think of a shopping list app where users add or remove items. Using {#each}, the app instantly shows the updated list without you rewriting HTML every time.
Manually writing repeated HTML is slow and error-prone.
{#each} automates creating HTML for lists.
This makes your code simpler, cleaner, and easier to maintain.