Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 35 ยท Templates and Markup

Lists with {#each}

Render lists in Svelte 5 with {#each}: index, keys for stable updates, destructuring, empty states and iterating over objects, Maps and ranges.

Most interfaces show collections: messages, products, search results. The {#each} block repeats markup for every item. It is simple to start with, and a single detail, the key, decides whether it also behaves correctly when the list changes.

The basics

SVELTE
<script>
  let fruits = $state(['apple', 'banana', 'cherry']);
</script>

<ul>
  {#each fruits as fruit}
    <li>{fruit}</li>
  {/each}
</ul>

Add the index as a second name:

SVELTE
{#each fruits as fruit, i}
  <li>{i + 1}. {fruit}</li>
{/each}

Because fruits is $state, fruits.push('date') adds a new <li> without any further work.

Destructuring

You can destructure arrays and objects right in the as clause:

SVELTE
{#each people as { name, age }}
  <p>{name} is {age}</p>
{/each}

{#each pairs as [key, value]}
  <p>{key}: {value}</p>
{/each}

Keyed each blocks

By default Svelte reuses the DOM for items by position. If you remove the first item, the first <li> is reused for what used to be the second, and its text is changed. That is fine for plain text, but it breaks when the nodes hold state: typed input, focus, running animations, or child component state.

A key tells Svelte how to identify each item. Put it in parentheses after the as clause:

SVELTE
{#each todos as todo (todo.id)}
  <li>
    <input type="checkbox" bind:checked={todo.done} />
    <input value={todo.text} />
  </li>
{/each}

Now when you delete todo number 2, exactly that <li> is removed and the others keep their typed text and focus. Rules for keys:

  • Use something unique and stable, like a database id.
  • Do not use the index as the key; that defeats the purpose.
  • Keys can be any value, but numbers and strings are typical.

Unkeyed (by position)

Reuse by index Row 1 stays row 1
State mismatch Inputs show wrong text
1 / 2

Empty lists with {:else}

SVELTE
{#each results as result (result.id)}
  <ResultCard {result} />
{:else}
  <p>No results found.</p>
{/each}

The {:else} branch runs when the list is empty (or the iterable has no items).

What can you iterate?

{#each} works with arrays and anything array-like or iterable (it uses Array.from under the hood). Examples:

SVELTE
{#each Array(5) as _, i}
  <span>{i}</span>
{/each}

{#each Object.entries(scores) as [name, score]}
  <p>{name}: {score}</p>
{/each}

{#each [...map] as [key, value]}
  <p>{key} = {value}</p>
{/each}

For a reactive Map, use SvelteMap from svelte/reactivity (deep reactivity), since a plain Map does not notify Svelte of changes.

Mutating items inside the loop

With a deeply reactive array of objects you can bind straight to item properties:

SVELTE
{#each todos as todo (todo.id)}
  <label>
    <input type="checkbox" bind:checked={todo.done} />
    {todo.text}
  </label>
{/each}

Svelte 5 allows bind: to an each item as long as the array is state (a proxy). If the array comes from props, the parent has to pass it as $bindable; see callbacks and bindable props.

Derived lists: filter and sort

Do not filter by mutating the source. Derive a view:

SVELTE
<script>
  let query = $state('');
  let items = $state(['pear', 'apple', 'plum', 'apricot']);
  let visible = $derived(
    items.filter((x) => x.includes(query)).toSorted()
  );
</script>

<input bind:value={query} placeholder="Filter" />
{#each visible as item (item)}<p>{item}</p>{/each}

toSorted returns a new array, leaving items untouched (plain sort would mutate the source).

Stand-in: why keys matter

This stand-in "renders" rows as objects that remember a typed value (like an input). It reconciles an updated list two ways, by position and by key, after the first item is deleted. Compare which row ends up holding the typed text.

JS Position versus key (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

By position, the text typed into the deleted row's input now sits next to label B. By key, nothing is left over: the deleted row took its input with it.

Filter and sort a list (stand-in page)

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does the key in {#each todos as todo (todo.id)} do?

    Keys let Svelte move, add and remove the right nodes, preserving their state.
  2. 2. Which is a poor choice of key?

    The index changes when items move or are removed, which defeats the point of keying.
  3. 3. When does the {:else} branch of {#each} render?

    {:else} is the empty state.
  4. 4. How should you filter a list in Svelte 5?

    Derived views keep the source data intact.

Summary

  • {#each list as item, index} repeats markup; arrays in $state update on push, splice and so on.
  • Use keys (item.id) when rows hold state, can reorder or can be removed.
  • {:else} renders the empty state.
  • Destructure items; derive filtered/sorted views instead of mutating the source.

Next: Events and Bindings