Skip to content

How to simulate a for loop in Svelte templates

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

I wrote 17 books to help you become a better developer, download them all at $0 cost by joining my newsletter

  • C Handbook
  • Command Line Handbook
  • CSS Handbook
  • Express Handbook
  • Git Cheat Sheet
  • Go Handbook
  • HTML Handbook
  • JS Handbook
  • Laravel Handbook
  • Next.js Handbook
  • Node.js Handbook
  • PHP Handbook
  • Python Handbook
  • React Handbook
  • SQL Handbook
  • Svelte Handbook
  • Swift Handbook

JOIN MY CODING BOOTCAMP, an amazing cohort course that will be a huge step up in your coding career - covering React, Next.js - next edition February 2025

Bootcamp 2025

Join the waiting list