Introduction to Control Flow in Svelte
Understanding the `#if` Block

The #if block is the simplest form of control flow in Svelte. It allows you to conditionally render content based on a boolean expression. If the expression evaluates to true, the content inside the #if block is displayed; otherwise, it’s hidden.

Here’s a basic example:

<script lang="ts">
  let isVisible = $state(false);
</script>

{#if isVisible}
  <p>This message is visible!</p>
{/if}

<button onclick={() => isVisible = !isVisible}>
  Toggle Visibility
</button>

In this example, the isVisible state variable controls whether the paragraph is displayed. Clicking the button toggles the value of isVisible, showing or hiding the message.

This is a simple yet powerful way to control what your users see based on the state of your application.

Adding `#else-if` and `#else` Blocks

While #if is great for simple conditions, you’ll often need to handle multiple conditions. This is where #else-if and #else come in. The #else-if block allows you to check additional conditions if the previous #if or #else-if block evaluates to false. The #else block provides a fallback for when none of the conditions are met.

Let’s look at an example where we display different messages based on a user’s role:

<script lang="ts">
  let userRole = $state<'admin' | 'editor' | 'viewer' | null>(null);
</script>

{#if userRole === 'admin'}
  <p>Welcome, Admin! You have full access.</p>
{:else if userRole === 'editor'}
  <p>Welcome, Editor! You can create and edit content.</p>
{:else if userRole === 'viewer'}
  <p>Welcome, Viewer! You can view content.</p>
{:else}
  <p>Please log in to access the system.</p>
{/if}

In this example, the message displayed depends on the value of userRole. If userRole is null, the #else block ensures a default message is shown. This structure makes it easy to handle complex logic while keeping your code clean and readable.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal