> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/sveltejs/svelte/llms.txt
> Use this file to discover all available pages before exploring further.

# Each Blocks

> Loop over arrays and iterables with {#each} blocks in Svelte

Iterate over values using `{#each}` blocks. Works with arrays, array-like objects (anything with a `length` property), and iterables like `Map` and `Set`.

## Basic Each Block

The simplest form iterates over an array:

```svelte theme={null}
{#each expression as name}...{/each}
```

### Example

```svelte theme={null}
<h1>Shopping list</h1>
<ul>
  {#each items as item}
    <li>{item.name} x {item.qty}</li>
  {/each}
</ul>
```

## With Index

Access the index (zero-based) as the second value:

```svelte theme={null}
{#each expression as name, index}...{/each}
```

### Example

```svelte theme={null}
{#each items as item, i}
  <li>{i + 1}: {item.name} x {item.qty}</li>
{/each}
```

## Keyed Each Blocks

Use a unique key to help Svelte efficiently update the list:

```svelte theme={null}
{#each expression as name (key)}...{/each}
```

<Warning>
  Always use keys when the list can be reordered, filtered, or items can be added/removed from the middle. This ensures correct DOM updates and preserves component state.
</Warning>

### Example

```svelte theme={null}
{#each items as item (item.id)}
  <li>{item.name} x {item.qty}</li>
{/each}

<!-- With index -->
{#each items as item, i (item.id)}
  <li>{i + 1}: {item.name} x {item.qty}</li>
{/each}
```

## Destructuring

You can destructure items directly in the each block:

<CardGroup cols={2}>
  <Card title="Object Destructuring">
    ```svelte theme={null}
    {#each items as { id, name, qty }, i (id)}
      <li>{i + 1}: {name} x {qty}</li>
    {/each}
    ```
  </Card>

  <Card title="Rest Patterns">
    ```svelte theme={null}
    {#each objects as { id, ...rest }}
      <li>
        <span>{id}</span>
        <MyComponent {...rest} />
      </li>
    {/each}
    ```
  </Card>

  <Card title="Array Destructuring">
    ```svelte theme={null}
    {#each items as [id, ...rest]}
      <li>
        <span>{id}</span>
        <MyComponent values={rest} />
      </li>
    {/each}
    ```
  </Card>

  <Card title="Nested Destructuring">
    ```svelte theme={null}
    {#each users as { id, profile: { name, avatar } }}
      <div>
        <img src={avatar} alt={name} />
        <span>{name}</span>
      </div>
    {/each}
    ```
  </Card>
</CardGroup>

## Each Without an Item

Render something `n` times without caring about the values:

```svelte theme={null}
{#each expression}...{/each}
```

### Example: Chess Board

```svelte theme={null}
<div class="chess-board">
  {#each { length: 8 }, rank}
    {#each { length: 8 }, file}
      <div class:black={(rank + file) % 2 === 1}></div>
    {/each}
  {/each}
</div>
```

## Else Blocks

Render fallback content when the list is empty:

```svelte theme={null}
{#each expression as name}...{:else}...{/each}
```

### Example

```svelte theme={null}
{#each todos as todo}
  <p>{todo.text}</p>
{:else}
  <p>No tasks today!</p>
{/each}
```

## Real-World Use Cases

<CardGroup cols={2}>
  <Card title="User List" icon="users">
    ```svelte theme={null}
    {#each users as user (user.id)}
      <div class="user-card">
        <img src={user.avatar} alt="{user.name}" />
        <h3>{user.name}</h3>
        <p>{user.email}</p>
      </div>
    {:else}
      <p>No users found</p>
    {/if}
    ```
  </Card>

  <Card title="Table Rows" icon="table">
    ```svelte theme={null}
    <table>
      <thead>
        <tr>
          <th>Name</th>
          <th>Price</th>
          <th>Stock</th>
        </tr>
      </thead>
      <tbody>
        {#each products as product (product.sku)}
          <tr>
            <td>{product.name}</td>
            <td>${product.price}</td>
            <td>{product.stock}</td>
          </tr>
        {/each}
      </tbody>
    </table>
    ```
  </Card>

  <Card title="Navigation Menu" icon="bars">
    ```svelte theme={null}
    <nav>
      {#each menuItems as item (item.path)}
        <a 
          href={item.path}
          class:active={$page.url.pathname === item.path}
        >
          {item.label}
        </a>
      {/each}
    </nav>
    ```
  </Card>

  <Card title="Tag List" icon="tag">
    ```svelte theme={null}
    <div class="tags">
      {#each tags as tag (tag)}
        <span class="tag">
          {tag}
          <button onclick={() => removeTag(tag)}>×</button>
        </span>
      {/each}
    </div>
    ```
  </Card>
</CardGroup>

## Working with Different Data Types

### Arrays

```svelte theme={null}
<script>
  let fruits = $state(['apple', 'banana', 'cherry']);
</script>

{#each fruits as fruit}
  <p>{fruit}</p>
{/each}
```

### Maps

```svelte theme={null}
<script>
  let userMap = $state(new Map([
    ['1', { name: 'Alice', role: 'Admin' }],
    ['2', { name: 'Bob', role: 'User' }]
  ]));
</script>

{#each userMap as [id, user] (id)}
  <div>{user.name} - {user.role}</div>
{/each}
```

### Sets

```svelte theme={null}
<script>
  let uniqueTags = $state(new Set(['svelte', 'javascript', 'web']));
</script>

{#each uniqueTags as tag (tag)}
  <span class="tag">{tag}</span>
{/each}
```

## Handling Null/Undefined

If the value is `null` or `undefined`, it's treated as an empty array:

```svelte theme={null}
{#each maybeNull as item}
  <p>{item}</p>
{:else}
  <p>No data available</p>
{/each}
```

## Nested Each Blocks

```svelte theme={null}
{#each categories as category (category.id)}
  <div class="category">
    <h2>{category.name}</h2>
    {#each category.items as item (item.id)}
      <div class="item">{item.name}</div>
    {/each}
  </div>
{/each}
```

## Performance Best Practices

1. **Always use keys** when items can be reordered or removed
2. **Use unique, stable keys** - prefer IDs over indexes
3. **Avoid creating new objects in the template** - they break key identity

```svelte theme={null}
<!-- Good: Stable key -->
{#each items as item (item.id)}
  <Item data={item} />
{/each}

<!-- Bad: Index as key when list can change -->
{#each items as item, i (i)}
  <Item data={item} />
{/each}

<!-- Bad: Creating new object -->
{#each items as item ({ id: item.id })}
  <Item data={item} />
{/each}
```
