Encodera

Thanks for reading!

Donate to the site — we work hard for you.

Contents

Conditions: the if block

Often a part of the page should be shown only under some condition: an "empty list" message, a button for a logged-in user, a form error. Svelte markup has the {#if} block for this.

The if block

The block opens with {#if condition} and closes with {/if}:

<!-- src/routes/+page.svelte -->
<script>
  let todos = $state([]);
</script>
 
{#if todos.length === 0}
  <p>The list is empty. Add your first task.</p>
{/if}
 
<button onclick={() => todos.push({ id: Date.now(), text: 'New', done: false })}>
  Add
</button>

While there are no tasks, the hint is visible. After clicking "Add" the condition becomes false and the paragraph disappears from the DOM — it is not hidden with a style but removed completely.

The else branch

For a second variant, add :

<script>
  let todos = $state([]);
</script>
 
{#if todos.length === 0}
  <p>The list is empty.</p>
{:else}
  <p>Tasks in the list: {todos.length}</p>
{/if}

Exactly one of the two paragraphs is always visible.

Several conditions

The {:else if ...} branch checks the next condition when the previous ones did not match:

<script>
  let todos = $state([
    { id: 1, text: 'Buy bread', done: true },
    { id: 2, text: 'Call Oleg', done: false }
  ]);
  let remaining = $derived(todos.filter((todo) => !todo.done).length);
</script>
 
{#if todos.length === 0}
  <p>The list is empty.</p>
{:else if remaining === 0}
  <p>All done!</p>
{:else}
  <p>Left: {remaining}</p>
{/if}

Now the page shows "Left: 1". Mark the second task as done and the text changes to "All done!".

Block syntax

SymbolMeaningExample
#opens a block{#if ok}
:continues a block
/closes a block{/if}

The same symbols appear in the each and await blocks.

Short conditions

For a simple case an expression is enough: {remaining > 0 ? 'Things to do' : 'Free'}. The {#if} block is needed when the markup changes depending on the condition, not just the text.

Common mistake

Writing else without the colon or forgetting to close the block:

<script>
  let ok = $state(true);
</script>
 
{#if ok}
  <p>Yes</p>
{else}
  <p>No</p>

The compiler reports an error. The right form is inside the block and a mandatory {/if} at the end.

Thanks for reading!

Donate to the site — we work hard for you.