CHAPTER 08
Beginner
Conditional Rendering and Loops
Updated: May 18, 2026
5 min read
# CHAPTER 8
Conditional Rendering and Loops
1. Chapter Introduction
Svelte provides clean block-based syntax for controlling what renders:{#if} for conditions, {#each} for loops, and {#await} for promises. These blocks make templates expressive without needing JSX ternaries or directive gymnastics.
2. Learning Objectives
-
Conditionally render elements using
{#if},{:else},{:else if}.
-
Render lists using
{#each}with and without keys.
-
Handle async data with
{#await}.
- Build a filterable product listing.
3. {#if} Blocks
svelte
4. {#each} Loops
svelte
5. {#await} for Async Data
svelte
6. Mini Project: Product Listing with Filters
svelte
7. Common Mistakes
-
No key in
{#each}: Without(item.id), DOM nodes are reused incorrectly on list changes.
-
{#if}for CSS visibility: Use CSS/transitions for visual toggling;{#if}destroys and recreates elements.
8. MCQs
Question 1
What opens a conditional block?
Question 2
What closes an {#if}?
Question 3
What is {:else if condition}?
Question 4
Purpose of key in {#each items as item (item.id)}?
Question 5
How to get index in each?
Question 6
What handles async loading/success/error?
Question 7
In {:then data}, what is data?
Question 8
What shows when array is empty?
Question 9
Can blocks be nested?
Question 10
Syntax for destructuring in each?
9. Interview Questions
-
Q: Why is keyed
{#each}important for performance?
-
Q: How does
{#await}simplify loading/success/error state management?
10. Summary
Svelte's template control flow is clean and powerful.{#if} handles conditions, {#each} renders lists efficiently with optional keys, and {#await} elegantly manages all three async states in one block.
11. Next Chapter Recommendation
In Chapter 9: Props and Component Communication, we build component hierarchies usingexport let and createEventDispatcher.