Iterate over values using {#each} blocks. Works with arrays, array-like objects (anything with a length property), and iterables like Map and Set.
Basic Each Block
The simplest form iterates over an array:
Example
With Index
Access the index (zero-based) as the second value:
Example
Keyed Each Blocks
Use a unique key to help Svelte efficiently update the list:
Always use keys when the list can be reordered, filtered, or items can be added/removed from the middle. This ensures correct DOM updates and preserves component state.
Example
Destructuring
You can destructure items directly in the each block:
Each Without an Item
Render something n times without caring about the values:
Example: Chess Board
Else Blocks
Render fallback content when the list is empty:
Example
Real-World Use Cases
Working with Different Data Types
Arrays
Maps
Sets
Handling Null/Undefined
If the value is null or undefined, it’s treated as an empty array:
Nested Each Blocks
- Always use keys when items can be reordered or removed
- Use unique, stable keys - prefer IDs over indexes
- Avoid creating new objects in the template - they break key identity