0
0
Svelteframework~5 mins

Else and else-if blocks in Svelte

Choose your learning style9 modes available
Introduction

Else and else-if blocks let you show different things on the screen depending on conditions. They help your app react to different situations.

Showing a message if a user is logged in, and a different one if not.
Displaying different content based on a selected option in a form.
Showing a loading spinner while data is loading, then showing the data or an error message.
Changing the page content based on user choices or app state.
Syntax
Svelte
{#if condition}
  <!-- content if true -->
{:else if anotherCondition}
  <!-- content if anotherCondition is true -->
{:else}
  <!-- content if none of the above are true -->
{/if}
Use {:else if} to check another condition if the first is false.
Use {:else} to show content when all conditions are false.
Examples
Shows a welcome message if loggedIn is true, otherwise asks to log in.
Svelte
{#if loggedIn}
  <p>Welcome back!</p>
{:else}
  <p>Please log in.</p>
{/if}
Shows different grades based on the score value.
Svelte
{#if score >= 90}
  <p>Grade: A</p>
{:else if score >= 80}
  <p>Grade: B</p>
{:else}
  <p>Grade: C or below</p>
{/if}
Sample Program

This Svelte component shows a loading message first. After 2 seconds, it changes to a success message. If the status was anything else, it would show a failure message.

Svelte
<script>
  let status = 'loading';

  // Simulate status change after 2 seconds
  setTimeout(() => {
    status = 'success';
  }, 2000);
</script>

{#if status === 'loading'}
  <p>Loading data...</p>
{:else if status === 'success'}
  <p>Data loaded successfully!</p>
{:else}
  <p>Failed to load data.</p>
{/if}
OutputSuccess
Important Notes

Only one block inside {#if} ... {:else if} ... {:else} runs at a time.

You can have multiple {:else if} blocks to check many conditions.

Make sure to close the block with {/if}.

Summary

Use {#if} to start a condition block.

Use {:else if} to check another condition if the first is false.

Use {:else} to show content when all conditions fail.