| | |

Svelte 21 🧔 Conditional Rendering Control Flow Blocks ({#if}, {:else if}, {:else})

ā±ļø Estimated read: 7 min | |

Svelte 5 continues the tradition of highly declarative UI logic by providing built-in control flow blocks. Conditional rendering—the ability to show or hide parts of the DOM based on reactive state—is fundamental to modern application development. By using syntax that lives directly within the markup, Svelte ensures that your UI logic remains tightly coupled to your data without requiring complex nested ternary operators or auxiliary function calls in JavaScript.

The control flow blocks in Svelte 5 are designed to be efficient and readable. When the reactive signal driving an {#if} block changes, Svelte updates the DOM in the most performant way possible, adding or removing elements only when necessary. This chapter walks through the syntax and usage patterns of the conditional block, explaining how to handle multiple branches and why this approach is preferred over standard JavaScript expression-based rendering.

Key point: Svelte conditional blocks are declarative structures that manage DOM creation and removal based on reactive state, ensuring the UI always reflects the current data while maintaining optimal performance.


Why Conditional Rendering Blocks exist

The complexity of nested ternaries. While JavaScript supports ternary operators, nesting them in templates leads to “spaghetti code” that is difficult to parse and debug. Block syntax provides a clear, structural visual guide.

The performance of targeted reconciliation. Unlike array-based map approaches in other frameworks, Svelte blocks are “first-class” citizens. The compiler understands exactly which DOM nodes belong to which block, allowing for granular updates rather than full-component re-renders.

The readability of structural intent. Seeing {#if} and {:else} allows a developer to immediately understand the layout logic of a component without interpreting functional logic or conditional style classes.

The scope safety. Control blocks create lexical scopes for their content. This allows Svelte to perform static analysis and ensure that variables are only accessed when the corresponding DOM nodes actually exist, preventing null pointer exceptions.

The declarative standard. By keeping logic inside the template, Svelte maintains a clear separation between side-effect-prone imperative code in script blocks and the descriptive layout of the UI.


a. The base {#if} block structure

The {#if} block is the foundation of conditional logic in Svelte. It checks a reactive variable (a signal) and mounts the children to the DOM only when the condition evaluates to true. When the condition becomes false, the DOM is pruned.

{#if isLoggedIn}
  <button>Log Out</button>
{/if}

The logic inside the block is reactive. If isLoggedIn is toggled in your script, Svelte automatically updates the UI. Because the block is managed by the Svelte compiler, it is aware of the component’s reactive dependency graph, meaning it will only re-evaluate when isLoggedIn specifically changes.

b. Chaining with {:else if} and {:else}

To handle complex logic involving multiple states, Svelte provides {:else if} and {:else} blocks. These allow you to sequence conditions gracefully without flattening the DOM with multiple independent if checks.

{#if role === 'admin'}
  <AdminPanel />
{:else if role === 'moderator'}
  <ModPanel />
{:else}
  <UserPanel />
{/if}

This structure is strictly evaluated from top to bottom. Once one condition is met, the remaining blocks are ignored. This efficiency ensures that even if you have a massive state object, the browser only ever has to manage the DOM nodes for the active branch of your conditional tree.

c. Scope and reactivity integration

One of the strengths of Svelte’s conditional blocks is their tight integration with state. Because these blocks are managed by the reactive system, you can use them to safely render data that might only exist under specific conditions, effectively acting as an optional guard for your application logic.

{#if user?.profile}
  <img src={user.profile.avatarUrl} alt="Avatar" />
{/if}

In the example above, the block acts as a null guard. Svelte’s reactivity system ensures that the user.profile object is only accessed if the condition is true. This prevents runtime errors that might occur if you tried to access a property on an undefined object before the data had finished loading from an API.


Complete Example Session

// ============================================
// PART 1: DEFINING STATE
// ============================================
let status = $state('loading'); // 'loading' | 'success' | 'error'

// ============================================
// PART 2: CONDITIONAL RENDERING
// ============================================
{#if status === 'loading'}
  <p>Please wait...</p>
{:else if status === 'success'}
  <button>Continue</button>
{:else}
  <p>Something went wrong.</p>
  <button onclick={() => status = 'loading'}>Retry</button>
{/if}

// ============================================
// PART 3: DYNAMIC UPDATES
// ============================================
function loadData() {
  status = 'loading';
  // simulated fetch...
  status = 'success';
}

This sequence covers the base if block, the chaining of else if and else, and the reactive update mechanism that toggles the UI visibility based on the internal state.


Quick Reference

Control Block Syntax

BlockPurpose
{#if cond}Starts the block
{:else if cond}Adds a middle condition
{:else}The fallback branch
{/if}Closes the block

Behavior Matrix

FeatureSvelte BlockJS Ternary
ReadabilityHighLow
DOM ReconciliationGranularFull update
Scope SafetyExcellentPoor
Multi-branchingEasyComplex

Best Practices

āœ… Do This:

{#if items.length > 0} 
  <List {items} />
{:else}
  <EmptyState />
{/if}                                                        // āœ…

{#if user.isAdmin} <AdminControls /> {/if}                  // āœ…

āŒ Don’t Do This:

{items.length > 0 ? <List items={items}/> : <EmptyState/>}  // āŒ

{#if a} <div></div> {/if}
{#if !a} <span></span> {/if}                                // āŒ

Common Pitfalls

PitfallWhy It HappensFix
Missing closerForgetting {/if}Ensure tags are paired
Logic leakageUsing complex expressionsUse $derived for logic
PerformanceToo many nested blocksSimplify component structure
State mismatchWrong conditional varAudit reactive signal

Real-World Examples

1. Auth gate

{#if user} <Dashboard /> {:else} <Login /> {/if}

2. Loading spinner

{#if loading} <Spinner /> {/if}

3. Role-based view

{#if role === 'admin'} <Admin /> {:else if role === 'user'} <Guest /> {/if}

4. Error handling

{#if error} <ErrorMsg msg={error} /> {/if}

5. Null guard

{#if data} {data.val} {/if}

6. Toggle switch

{#if visible} <div>Content</div> {/if}

7. Mobile vs Desktop

{#if isMobile} <MobileMenu /> {:else} <Nav /> {/if}

8. Validation feedback

{#if touched && !valid} <p>Invalid</p> {/if}

9. Theme switcher

{#if theme === 'dark'} <DarkIcon /> {:else} <LightIcon /> {/if}

10. Empty collection

{#if list.length === 0} <p>No items</p> {/if}

Visual

Conditional Branching Structure

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  CONDITION CHECK (Signal)            │
│  │                                   │
│  ā”œā”€ā”€ TRUE  ──► Render Block A        │
│  │                                   │
│  └── FALSE ──► Check Block B         │
│                │                     │
│                ā”œā”€ā”€ TRUE  ──► Render B│
│                │                     │
│                └── FALSE ──► Render C│
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

DOM Reconciliation

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  STATE: False ──► True               │
│                                      │
│  DOM:                                │
│  [Hidden] ──► [Mount Element]        │
│  [Cleanup] ◄── [State: False]        │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Scoping Illustration

ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”
│  {#if user}                          │
│    // user scope exists here         │
│  {/if}                               │
│  // user scope undefined here        │
ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜

Summary

ItemValue
Block Start{#if}
Middle{:else if}
Fallback{:else}
Block End{/if}
ReactivityAutomatic

Key takeaways:

  • Prefer control flow blocks. They are more readable, performant, and safer than ternary operators inside templates.
  • Granular updates. Svelte tracks dependencies precisely, so the DOM only updates when the condition result changes.
  • Use for null protection. Conditional blocks naturally guard against accessing properties on undefined or null objects.
  • Chain logically. Use {:else if} for sequences to keep your code clean and prevent overly deep nesting.
  • Maintain scope. Variable access inside the block is protected, making it easy to reason about data existence.

Remember: Conditional rendering blocks are the backbone of dynamic Svelte interfaces. They turn your application data into visual reality by providing a clean, structural way to dictate what the user sees based on their interaction with the app. By using them consistently, you ensure your template remains descriptive, high-performing, and easy to maintain as your application grows in complexity.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

šŸ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
āœ… Finance (Mortgage, Interest, Inflation)
āœ… Tech (Base64, JSON, Dev Suite, IP)
āœ… Health (BMI, BMR, TDEE)
āœ… Productivity (Timer, Workspace, QR)

āš”ļø Fast & Private
šŸ”’ No data leaves your device
šŸ’Ž 100% Free

šŸ”— Use it now: https://tools.kandz.me
šŸ”– Bookmark it—you’ll need it later!