0
0
Svelteframework~10 mins

If blocks ({#if}) in Svelte - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - If blocks ({#if})
Start
Evaluate condition
Render if-block content
No
Render else-block content (optional)
End
The Svelte {#if} block checks a condition. If true, it shows the if-block content. Otherwise, it shows the else-block content if present.
Execution Sample
Svelte
<script>
  let loggedIn = false;
</script>

{#if loggedIn}
  <p>Welcome back!</p>
{:else}
  <p>Please log in.</p>
{/if}
This code shows a welcome message if loggedIn is true, otherwise it asks the user to log in.
Execution Table
StepCondition (loggedIn)ResultBranch TakenRendered Output
1falsefalseelse branch<p>Please log in.</p>
2truetrueif branch<p>Welcome back!</p>
3falsefalseelse branch<p>Please log in.</p>
💡 Execution stops after rendering the appropriate block based on loggedIn value.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
loggedInfalsefalsetruefalse
Key Moments - 2 Insights
Why does the else block render when loggedIn is false?
Because the condition loggedIn is false (see execution_table step 1), Svelte renders the else block content.
What happens if there is no {:else} block and the condition is false?
No content is rendered for the if block when the condition is false, so nothing shows in that place.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is rendered at step 2?
A<p>Welcome back!</p>
B<p>Please log in.</p>
CNothing
DError
💡 Hint
Check the 'Rendered Output' column for step 2 in the execution_table.
At which step does the condition loggedIn become true?
AStep 1
BStep 2
CStep 3
DNever
💡 Hint
Look at the 'Condition (loggedIn)' column in execution_table and variable_tracker.
If loggedIn is always false and there is no {:else} block, what will render?
AThe if block content
BThe else block content
CNothing
DAn error
💡 Hint
Refer to key_moments about behavior when no else block exists and condition is false.
Concept Snapshot
Svelte {#if} block syntax:
{#if condition}
  <!-- shown if true -->
{:else}
  <!-- shown if false (optional) -->
{/if}

It shows content based on condition truthiness.
If no else block and condition is false, shows nothing.
Full Transcript
In Svelte, the {#if} block lets you show or hide content based on a condition. When the condition is true, the content inside the if block appears. If the condition is false and you have an {:else} block, that content shows instead. If no else block exists and the condition is false, nothing is shown. This visual trace shows how the loggedIn variable controls which message appears. When loggedIn is false, the else message 'Please log in.' is rendered. When loggedIn is true, the welcome message appears. This helps beginners see exactly how Svelte decides what to display.