Skip to content

How to simulate a for loop in Svelte templates

The Valley of Code

Your Web Development Manual

Svelte templates offer us the fantastic each block that lets us iterate on an array, or anything that is iterable:

let goodDogs = ['Roger', 'Syd']

{#each goodDogs as goodDog}

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}
β†’ Get my Svelte Handbook
  • THE VALLEY OF CODE (+ PRO), your web development manual
  • I wrote 15+ free coding BOOKS, download them here
  • SOLOPRENEUR LAND the missing MBA for wannabe solopreneurs craving a life with more freedom, control, fulfillment and purpose (summer 2024)