How to simulate a for loop in Svelte templates
New Course Coming Soon:
Get Really Good at Git
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}
Are you intimidated by Git? Can’t figure out merge vs
rebase? Are you afraid of screwing up something any time
you have to do something in Git? Do you rely on ChatGPT
or random people’s answer on StackOverflow to fix your
problems? Your coworkers are tired of explaining Git to
you all the time? Git is something we all need to use,
but few of us really master it. I created this course to
improve your Git (and GitHub) knowledge at a radical
level. A course that helps you feel less frustrated with
Git. Launching Summer 2024. Join the waiting list!
→ Get my Svelte Handbook
Here is how can I help you:
- COURSES where I teach everything I know
- THE VALLEY OF CODE your web development manual
- BOOTCAMP 2024 cohort in progress, next edition in 2025
- BOOKS 16 coding ebooks you can download for free on JS Python C PHP and lots more
- SOLO LAB everything I know about running a lifestyle business as a solopreneur
- Interesting links collection
- Follow me on X