How Conditional Logic (IF ELSE) Works in Svelte 3?

Ashutosh Kukreti

If you're familiar with Angular or Vue, they use framework-specific attributes to implement conditional logic. Angular supports ngIf while Vue uses v-if. Svelte uses {#if} {/if} syntax.

Implementation of IF

Conditional logic in the Svelte (component) HTML section begins with {#if }, and the condition is any valid JavaScript expression. It ends with {/if}.

For example, we can render an assessment of a color as follows:

{#if isAdmin === 1}
	<div> Hello Administrator. </div>
{/if}

Implementation of IF-ELSE

Conditional IF-ELSE logic in the Svelte (component) HTML section begins with {#if }, and the condition is any valid JavaScript expression. And then else with {:else}.It ends with {/if}.

{#if isAdmin === 1}
	<div> Hello Administrator. </div>
{:else}
	<div> You're a normal user. </div>
{/if}

Implementation of IF-ELSE IF -ELSE

Conditional IF-ELSE logic in the Svelte (component) HTML section begins with {#if }, and the condition is any valid JavaScript expression. And then else with {:else if}.It ends with {/if}.

{#if isAdmin === 1}
	<div> Hello Administrator. </div>
{:else if isSupervisor === 1 }
	<div> You're a supervisor. </div>
{:else }
	<div> You're a normal user. </div>
{/if}
Svelte3Beginners