Skip to main content
Svelte Fundamentals
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
123456789101112131415161718
<script>
  let isLoggedIn = false;
  let role = &#039;user';
</script>

{#if isLoggedIn}
  <p>Welcome back!</p>
{:else}
  <button>Log In</button>
{/if}

{#if role === 'admin'}
  <div>Admin Panel</div>
{:else if role === &#039;moderator'}
  <div>Mod Panel</div>
{:else}
  <div>User Dashboard</div>
{/if}

4. {#each} Loops

svelte
123456789101112131415161718192021
<script>
  let products = [
    { id: 1, name: &#039;Laptop', price: 999 },
    { id: 2, name: &#039;Phone', price: 599 }
  ];
</script>

<!-- With index -->
{#each products as product, i (product.id)}
  <div>{i + 1}. {product.name} — ${product.price}</div>
{:else}
  <p>No products found.</p>
{/each}

<!-- Destructuring -->
{#each products as { id, name, price } (id)}
  <div class="card">
    <h3>{name}</h3>
    <p>${price}</p>
  </div>
{/each}

5. {#await} for Async Data

svelte
12345678910111213
<script>
  let productsPromise = fetch(&#039;https://fakestoreapi.com/products?limit=5').then(r => r.json());
</script>

{#await productsPromise}
  <p>Loading...</p>
{:then products}
  {#each products as product (product.id)}
    <div>{product.title} — ${product.price}</div>
  {/each}
{:catch error}
  <p>Error: {error.message}</p>
{/await}

6. Mini Project: Product Listing with Filters

svelte
123456789101112131415161718192021222324252627282930313233343536
<script>
  let products = [
    { id: 1, name: &#039;MacBook', price: 1999, category: 'Laptops', inStock: true },
    { id: 2, name: &#039;iPhone', price: 999, category: 'Phones', inStock: true },
    { id: 3, name: &#039;iPad', price: 749, category: 'Tablets', inStock: false }
  ];
  let search = &#039;';
  let category = &#039;All';
  let categories = [&#039;All', 'Laptops', 'Phones', 'Tablets'];

  $: filtered = products.filter(p =>
    p.name.toLowerCase().includes(search.toLowerCase()) &&
    (category === &#039;All' || p.category === category)
  );
</script>

<input bind:value={search} placeholder="Search..." />
<select bind:value={category}>
  {#each categories as c}<option>{c}</option>{/each}
</select>

{#if filtered.length === 0}
  <p>No products found.</p>
{:else}
  {#each filtered as p (p.id)}
    <div class="card" class:out-of-stock={!p.inStock}>
      <h3>{p.name}</h3>
      <p>${p.price}</p>
      {#if p.inStock}
        <button>Add to Cart</button>
      {:else}
        <span>Out of Stock</span>
      {/if}
    </div>
  {/each}
{/if}

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 using export let and createEventDispatcher.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·