0
0
Svelteframework~10 mins

Else and else-if blocks in Svelte - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Else and else-if blocks
Start
Check if condition1
Render block1
Render block2
End
Svelte checks conditions in order: if, else-if, then else. It renders the first true block and skips the rest.
Execution Sample
Svelte
<script>
  let count = 2;
</script>

{#if count === 1}
  <p>One</p>
{:else if count === 2}
  <p>Two</p>
{:else}
  <p>Other</p>
{/if}
This Svelte code shows how else-if and else blocks decide which paragraph to show based on count.
Execution Table
StepCondition CheckedCondition ResultBlock Rendered
1count === 1FalseNo
2count === 2True<p>Two</p>
3else blockSkippedNo
💡 Condition count === 2 is true, so else-if block renders and else block is skipped.
Variable Tracker
VariableStartAfter Step 1After Step 2Final
count2222
Key Moments - 2 Insights
Why does the else block not render even though it exists?
Because the else-if condition (count === 2) was true at step 2, Svelte renders that block and skips the else block as shown in execution_table row 3.
What happens if the first if condition is true?
If the first if condition is true, Svelte renders that block immediately and skips all else-if and else blocks, similar to step 1 in the table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what block is rendered at step 2?
A<p>Two</p>
B<p>One</p>
C<p>Other</p>
DNo block
💡 Hint
Check the 'Block Rendered' column at step 2 in the execution_table.
At which step does Svelte decide to skip the else block?
AStep 1
BStep 3
CStep 2
DNever
💡 Hint
Look at the 'Condition Result' and 'Block Rendered' columns for step 2 and 3.
If count was 3, which block would render according to the execution flow?
A<p>Two</p>
B<p>Other</p>
C<p>One</p>
DNo block
💡 Hint
Refer to the concept_flow and see what happens when all conditions are false.
Concept Snapshot
Svelte uses {#if} for conditions.
Use {:else if} for additional checks.
Use {:else} for fallback.
Only the first true block renders.
Others are skipped.
Syntax example:
{#if cond1} ... {:else if cond2} ... {:else} ... {/if}
Full Transcript
This visual execution shows how Svelte processes else and else-if blocks. It starts by checking the first if condition. If true, it renders that block and stops checking. If false, it checks else-if conditions in order. The first true else-if block renders and stops further checks. If none are true, the else block renders as a fallback. In the example, count is 2, so the else-if block renders. The else block is skipped. Variables remain unchanged during this flow. This helps beginners see exactly how Svelte chooses which block to show.