How to simulate a for loop in Svelte templates
New Courses Coming Soon
Join the waiting lists
Svelte templates offer us the fantastic each block that lets us iterate on an array, or anything that is iterable:
<script>
let goodDogs = ['Roger', 'Syd']
</script>
{#each goodDogs as goodDog}
<li>{goodDog}</li>
{/each}
But what if you want to repeat a block for a few times, based on a variable? Let’s say we have the rows
variable that holds a number, and we want to use that as the loop variable.
We can do what we need by creating an array, using the Array(n)
syntax. This will create an array, initializing it with n
items:
{#each Array(rows) as _, row}
{row}
{/each}
→ Get my Svelte Handbook
Here is how can I help you:
- COURSES where I teach everything I know
- CODING BOOTCAMP cohort course - next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- Follow me on X