List Rendering in Svelte

{#each array as item} ... {/each} draws the markup inside once per item, in order. {#each array as item, i} gives the index i, the number of each item…

The stall's menu has 3 items today, maybe 12 tomorrow. You don't want to type each <li> by hand every time the menu changes. What you need: one row template, and Svelte repeats it for every item in the array. This is called list rendering, and in Svelte you do it with an {#each} block. In React you use .map() in JSX, and in Vue you use v-for.

Picture the menu board at Mrs. Sri's stall. Mrs. Sri doesn't write each row by hand. She has one row template, "name, price", and prints it once for every dish in her notebook. When she adds a dish to the notebook, the board grows by one row. In code, the markup inside {#each} is that row template, the array is the notebook, and the page is the menu board.

{#each}: one template, repeated per item

This code shows three dishes as a list of <li>:

<script>
  let menu = ["Fried Rice", "Chicken Noodles", "Iced Tea"]
</script>

<ul>
  {#each menu as item}
    <li>{item}</li>
  {/each}
</ul>

The result on the page:

<ul>
  <li>Fried Rice</li>
  <li>Chicken Noodles</li>
  <li>Iced Tea</li>
</ul>

In the first exercise, the code is exactly this, with let fruits = ["Apple", "Mango", "Orange"]: the first <li> holds Apple and the last one Orange. Each <li> holds just {item}, with no text you type yourself.

Row numbers: the index

If you also need the round's number, add a second name after a comma:

{#each menu as item, i}
  <li>{i + 1}. {item}</li>
{/each}

The result is 1. Fried Rice, 2. Chicken Noodles, 3. Iced Tea. This second name, i, is the index: the round's number, starting at 0, like array indexes in JavaScript. So add 1 when the numbers should start at 1.

An array of objects

A real menu has a name, a price and an id:

<script>
  let menu = [
    { id: 1, name: "Fried Rice", price: 15 },
    { id: 2, name: "Chicken Noodles", price: 12 },
    { id: 3, name: "Iced Tea", price: 5 },
  ]
</script>

<ul>
  {#each menu as item, i}
    <li>{i + 1}. {item.name}: ${item.price.toFixed(2)}</li>
  {/each}
</ul>

The result is 1. Fried Rice: $15.00, 2. Chicken Noodles: $12.00, 3. Iced Tea: $5.00.

{:else}: when the array is empty

An {#each} block can also have an {:else} branch:

<ul>
  {#each cart as item}
    <li>{item}</li>
  {:else}
    <li>The cart is still empty</li>
  {/each}
</ul>

When cart holds [], only The cart is still empty shows. As soon as cart has items, that message disappears and the rows appear. You don't need to write an {#if cart.length === 0} of your own.

Keyed each: (item.id)

Say menu is made with $state, every menu row has a note field (an <input>), and the list is drawn without a key. A key is a label that identifies each item, covered below. A customer types "spicy" in the Fried Rice row. Then the first row is removed with menu = menu.slice(1), which makes a new array without the first item. Guess: is the note "spicy" removed with it, or does it move to the Chicken Noodles row?

Without a key, Svelte matches rows to items by position. When the array goes from 3 items to 2, Svelte reuses the first and second row elements. It replaces their text with the item that is now at that position, then removes the last row element. What's typed in an <input> belongs to the element, not to the data. So it stays in the reused element:

<li> element Before After, no key After, with key
Row 1 Fried Rice, note "spicy" Chicken Noodles, note "spicy" (removed)
Row 2 Chicken Noodles Iced Tea Chicken Noodles
Row 3 Iced Tea (removed) Iced Tea

Without a key, the note "spicy" moves to Chicken Noodles. Fried Rice does leave the list, but the element that is removed is the Iced Tea element in the bottom row.

A key tells Svelte how to recognise each item:

{#each menu as item (item.id)}
  <li>
    {item.name}
    <input placeholder="note" />
  </li>
{/each}

Adding and removing items

A list that can change is made with $state. Svelte records every change to the content of a $state array, so the usual array methods update the page right away:

let menu = $state([ /* the three dishes from before */ ])

menu.push({ id: 4, name: "Iced Orange", price: 7 })    // add at the end
menu.splice(0, 1)                                    // drop the first item
menu = menu.filter((m) => m.id !== 2)                // drop Chicken Noodles

Replacing the array with a new one, such as menu = menu.filter(...) or menu = menu.slice(1), works too. What doesn't work: a plain let array. Without $state, menu.push(...) does add to the array, but no new row appears on the page.

Older code: Svelte 4

In Svelte 4 code, {#each}, the index, the key and {:else} are written exactly the same. The difference is the state: the array is a plain let, and the list only changes when there's an assignment. menu.push(...) alone doesn't make a new row appear. That is why older code is full of menu = [...menu, item], or menu = menu after a push.

⚠️ What breaks a list

TL;DR: {#each array as item} ... {/each} draws the markup inside once per item, in order. {#each array as item, i} gives the index i, the number of each item, starting from 0, so write {i + 1} for numbers from 1. {:else} inside {#each} shows when the array is empty. Without a key (a label that identifies each item), Svelte matches rows to items by position, so what's typed in an <input> can move to another item when a row is removed. With the key (item.id), every row follows its item. A key must be unique, and the index isn't a good key. A list that can change is made with $state, so push and splice update the page right away. The exercises: {#each fruits as item} with <li>{item}</li> gives Apple through Orange, and {#each users as user, i (user.id)} with <li>{i + 1}. {user.name}</li> gives 1. Andi and 2. Budi.

⚡ One template, repeated per item

Write:

<script>
  let menu = ["Fried Rice", "Chicken Noodles", "Iced Tea"]
</script>

<ul>
  {#each menu as item}
    <li>{item}</li>
  {/each}
</ul>

Meaning: {#each menu as item} opens a loop (a part that repeats) over the array menu, and {/each} closes it. The markup inside is the row template: Svelte draws it once per item, so three items give three <li>. On each round (one pass of the loop), item holds one value of the array. You choose the name item.

⚡ Row numbers from the index

Write:

{#each menu as item, i}
  <li>{i + 1}. {item}</li>
{/each}
Guess first: i is the row's index, like an array index in JavaScript. On the first row, what does i hold?

Zero. The index starts at 0. That's why you write {i + 1} so the numbers start at 1.

Meaning: The second name after the comma, i, is the index: the round's number, starting at 0. One more thing: when the array is empty, an {:else} branch inside {#each} shows instead.

⚡ A key: (item.id)

Write:

{#each menu as item (item.id)}
  <li>
    {item.name}
    <input placeholder="note" />
  </li>
{/each}
Guess first: with no key (a label that identifies each item), Svelte matches rows to items by position. A customer types "spicy" in the note field of the Fried Rice row, then the first row is removed. Is the note removed with it, or does it move to Chicken Noodles?

It moves to Chicken Noodles. Svelte reuses the first row's element for Chicken Noodles, and what's typed in an <input> belongs to the element, not to the data.

Meaning: Here each item of menu is an object with an id and a name. The key (item.id) is written in parentheses after as item, so Svelte recognises rows by id. With a key, every row follows its item, including what's typed in its <input>. A key must be unique, and the index isn't a good key.

What you will learn