0
0
Svelteframework~3 mins

Why Each blocks ({#each}) in Svelte? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

Discover how a tiny loop can save you hours of tedious work and bugs!

The Scenario

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.

The Problem

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.

The Solution

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.

Before vs After
Before
<ul>\n  <li>Item 1</li>\n  <li>Item 2</li>\n  <li>Item 3</li>\n</ul>
After
<ul>\n  {#each items as item}\n    <li>{item}</li>\n  {/each}\n</ul>
What It Enables

You can easily display and update lists of any size with clean, simple code that stays correct as your data changes.

Real Life Example

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.

Key Takeaways

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.