Looping through arrays (lists)

In Svelte you can loop through arrays

{#each [name array] [item-in-array]}
<!-- Code here ->
{/each}
---
<script>
  let list = ['apple', 'banana', 'cherry'];
</script>

<h2>This is a looped component</h2>
<ul>
  {#each list as item}
    <li>{item}</li>
  {/each}
</ul>

You can also display something if the array is empty

{#each [name array] [item-in-array]}
<!-- Code here ->
{:else}
<!-- Code here ->
{/each}

You can also get the index (number) of the current item in the array:

{#each [name array] [item-in-array], [index]}
<!-- Code here ->
{/each}
---
<script>
  let list = ['apple', 'banana', 'cherry'];
</script>

<h2>This is a looped component</h2>
<ul>
  {#each list as item, index}
    <li>{index} {item}</li>
  {/each}
</ul>

Last updated