| | |

Svelte 22 ๐Ÿงก Iterative List Rendering Blocks ({#each} and {:else})

โฑ๏ธ Estimated read: 7 min | |

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

BlockPurpose
{#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

TypeStabilityRecommendation
PositionalLowAvoid if list changes
ID/Unique KeyHighAlways 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

PitfallWhy It HappensFix
Lost StateMissing keys on reorderAdd unique key
Memory LeakMissing cleanup on deleteUse component lifecycle
Empty listsMissing {:else} branchAdd {:else} block
Sync errorsModifying array in placeUse 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

ItemValue
Block Start{#each}
Fallback{:else}
Identity(key)
Indexas item, i
ReactiveAutomatic

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 checking length in an {#if} block.
  • Leverage indices only when necessary. Capture the index i only 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.

Was this helpful?


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!