Svelte 22 ๐งก Iterative List Rendering Blocks ({#each} and {:else})
Modern web applications are almost entirely data-driven, and rendering collections of data is a core task in virtually every UI. Svelte handles this with the {#each} block, a declarative syntax that maps arrays of data to individual DOM elements. By keeping iteration logic inside the template, Svelte minimizes the need for manual DOM manipulation or complex array transformations, ensuring that the rendered UI stays perfectly in sync with the underlying state.
In Svelte 5, the {#each} block is highly optimized. It not only handles simple list generation but also allows for key-based reconciliation, ensuring that when an array is reordered, added to, or deleted from, the DOM only undergoes the necessary minimal changes. This chapter explains the syntax, the importance of keying for performance, and the use of the {:else} branch to handle empty collections gracefully.
Key point: {#each} blocks render a collection of data into the DOM; use unique keys for stable reconciliation, and include an {:else} block to define the UI for empty or undefined arrays.
Why iterative blocks exist
The complexity of manual sync. Before list-rendering blocks, developers had to manually clear and rebuild DOM trees when data changed. Iterative blocks automate this sync between the reactive array and the live document.
The performance of key-based reconciliation. Without keys, updating an array often causes the framework to re-render the entire list. Keyed {#each} blocks allow Svelte to track individual items, ensuring only changed nodes are touched.
The readability of structural loops. JavaScriptโs .map() inside a template is often clunky. The {#each} block provides a clean, visual structure that clearly separates loop logic from standard HTML.
The fallback state requirement. Lists are often empty initially, especially when fetching data. The {:else} branch provides a declarative way to display “Empty State” components without additional conditional logic.
The index tracking necessity. In many UI patterns, like numbered lists or specific row-based interactions, the item’s index is required. {#each} provides this access natively without external state trackers.
a. Basic iteration and index access
The standard {#each} block takes an array as its source. You define the variable name for each item within the block, and optionally, you can capture the current index by providing a second argument.
<ul>
{#each items as item, index}
<li>{index + 1}: {item.name}</li>
{/each}
</ul>
This logic is entirely reactive. If you modify the items arrayโsuch as pushing a new object or slicing an existing oneโSvelte will automatically update the DOM nodes. The index variable updates automatically as well, keeping your numbered lists or row-based positioning correct at all times.
b. The {:else} fallback block
Often, you don’t want to render an empty list; you want to render a message or a specific component telling the user there’s nothing to see. The {:else} block is specifically designed for this purpose. It renders only if the array provided to the {#each} block is empty or undefined.
{#each tasks as task}
<Task {task} />
{:else}
<p>No tasks found. Relax!</p>
{/each}
This reduces the need for “if-list-length-is-zero” conditional wrappers. By combining the iteration and the fallback state into a single declarative structure, you improve template readability and reduce the surface area for logic errors.
c. The necessity of keyed blocks
When working with arrays that change (reordering, prepending, deleting), Svelte needs a way to identify which element is which. By default, Svelte tracks items by their position in the array. If you reorder the array, Svelte might re-render every single DOM node. Using a unique key (like an ID) allows Svelte to map a DOM node to a data item permanently.
{#each items as item (item.id)}
<Task {item} />
{/each}
The key (the expression in parentheses) must be unique. When the array is reordered, Svelte uses this key to move the existing DOM node to the new position instead of destroying and recreating it. This is not just a performance optimization; it preserves local DOM state, such as input focus or CSS transition states, which would otherwise be lost during a full component re-render.
Complete Example Session
// ============================================
// PART 1: DEFINING THE COLLECTION
// ============================================
let todos = $state([{ id: 1, text: 'Learn Svelte' }]);
// ============================================
// PART 2: ITERATING WITH KEYS
// ============================================
{#each todos as todo (todo.id)}
<div>
<span>{todo.text}</span>
<button onclick={() => remove(todo.id)}>Delete</button>
</div>
{:else}
<p>All clear!</p>
{/each}
// ============================================
// PART 3: MUTATION LOGIC
// ============================================
function remove(id: number) {
todos = todos.filter(t => t.id !== id);
}
function add() {
todos.push({ id: Math.random(), text: 'New Todo' });
}
This sequence illustrates the full lifecycle: defining a keyed list, rendering it with an empty-state fallback, and performing reactive mutations that update the UI while preserving item identity.
Quick Reference
Block Syntax
| Block | Purpose |
|---|---|
{#each arr as item} | Standard loop |
{#each arr as item, i} | Loop with index |
{#each arr as item (key)} | Keyed loop (stable) |
{:else} | Empty state fallback |
Keying Rules
| Type | Stability | Recommendation |
|---|---|---|
| Positional | Low | Avoid if list changes |
| ID/Unique Key | High | Always use |
Best Practices
โ Do This:
{#each items as item (item.id)}
<Item {item} />
{:else}
<p>List is empty</p>
{/each} // โ
// Always use unique IDs as keys
โ Don’t Do This:
{#each items as item}
<Item {item} />
{/each} // โ
// Don't use index as key if list order changes
{#each items as item, i (i)} // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Lost State | Missing keys on reorder | Add unique key |
| Memory Leak | Missing cleanup on delete | Use component lifecycle |
| Empty lists | Missing {:else} branch | Add {:else} block |
| Sync errors | Modifying array in place | Use assignment for reactivity |
Real-World Examples
1. Simple list
{#each list as item}<li>{item}</li>{/each}
2. Keyed list with index
{#each items as item, i (item.id)}<span>{i}: {item.val}</span>{/each}
3. Empty state message
{#each users as u} ... {:else} No users {/each}
4. Table rows
{#each rows as row (row.id)}<tr><td>{row.val}</td></tr>{/each}
5. Dynamic gallery
{#each photos as p (p.url)}<img src={p.url} />{/each}
6. Dropdown options
{#each options as opt}<option value={opt}>{opt}</option>{/each}
7. Tag cloud
{#each tags as t}<span class="tag">{t}</span>{/each}
8. Notification stack
{#each notes as n (n.id)}<Toast {n} />{/each}
9. Accordion list
{#each sections as s (s.id)}<Accordion {s} />{/each}
10. Breadcrumbs
{#each paths as p, i}<a href={p}>{p}</a>{/each}
Visual
List Reconciliation Process
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ ARRAY [A, B, C] โ
โ โ
โ DOM [ <A>, <B>, <C> ] โ
โ โ
โ ACTION: Reverse Array [C, B, A] โ
โ โ
โ KEYED RECONCILIATION: โ
โ Move <C> to start, <A> to end โ
โ (DOM nodes stay alive!) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The {:else} Fallback
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INPUT ARRAY: [] โ
โ โ
โ BLOCK EVALUATION: โ
โ {#each} ... (Skipped) โ
โ {:else} ... (Rendered) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Index vs. Key Identity
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ INDEX (0, 1, 2) โ
โ - Changes if item moves โ
โ - Bad for identity โ
โ โ
โ ID (Unique String/Int) โ
โ - Stays with item forever โ
โ - Good for identity โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Block Start | {#each} |
| Fallback | {:else} |
| Identity | (key) |
| Index | as item, i |
| Reactive | Automatic |
Key takeaways:
- Use keys for stability. Always provide a unique key (like
todo.id) to{#each}blocks if the list order can change or if items can be added/removed. - Declarative empty states. Use the
{:else}block to handle empty lists; it’s cleaner and more readable than checkinglengthin an{#if}block. - Leverage indices only when necessary. Capture the index
ionly if you need to display row numbers or specific positional data. - Maintain reactive arrays. Ensure the array being iterated is reactive so that Svelte detects pushes, slices, and filters.
- Preserve DOM state. Keyed blocks keep your UI inputs, focus, and animations intact by moving DOM elements rather than destroying them.
Remember: The {#each} block is your primary tool for data-driven UI. By using it correctlyโwith keys for identity and fallback blocks for empty statesโyou ensure that your application feels fast, responsive, and correct, even as your data structures become complex. It is the bridge that transforms raw JavaScript arrays into the rich, interactive lists that power the web.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!