How if-else Logic works in Svelte

📣 Sponsor

Like other modern frameworks such as Vue and React, Svelte allows for logic within components itself. In this article, we'll look at how if and else statement logic works in Svelte outside of Javascript. If you're brand new to Svelte, start with my guide on creating your first Svelte application.

Using if-else Statements in Svelte

Let's create a new component. Make a new file in your Svelte project in ./src/components called Component.svelte.

Inside that component, add the following code:

<script> // we write export let to say that this is a property // that means we can change it later! export let x = 0; const addToCounter = function() { ++x; } </script> <button id="counter" on:click="{addToCounter}">{x}</button> <style> button { background: #ffb334; border-radius: 8px; border: none; font-weight: bold; cursor: pointer; padding: 0.5rem 2rem; color: white; font-size: 1.5rem; } </style>

This simple component creates a counter which adds 1 to its value every time you click it. Let's look at how we'd use inline logic in this example.

If Statement Logic in Svelte

Logic in Svelte goes inside {} curly brackets. Suppose we want a message to display based on the value of x from our component above. Our logic should be:

  • if the value is more than 5 and less than 10, show "more than 5 clicks!"
  • if the value is more than 10, show "wow that's a lot of a clicks!"
  • otherwise show "keep clicking!"

In Svelte, the syntax for that looks like this:

<script> export let x = 0; const addToCounter = function() { ++x; } </script> {#if x 5} <h2>more than 5 clicks!</h2> {:else if x > 10} <h2>wow that's a lot of clicks!</h2> {:else} <h2>keep clicking!</h2> {/if} <button id="counter" on:click="{addToCounter}">{x}</button>

This means we don't have to rely on Javascript functions to write out which title we want to display - instead we can write it straight into our Svelte components.

if-else statements in Svelte

Similar to before, if you only wanted to have an if and an else, you can do that too:

{#if x <= 10 && x > 5} <h2>more than 5 clicks!</h2> {:else} <h2>keep clicking!</h2> {/if}

And finally, an if statement alone also works - perfect for hiding or displaying DOM elements based on Javascript values:

{#if x <= 10 && x > 5} <h2>more than 5 clicks!</h2> {/if}

Structure of if-else statements in Svelte

  • The first part of the if statement always starts with {#if STATEMENT} where STATEMENT is any logical Javascript statement we want to test out.
  • If we continue with else if or else, it's written as {:else if STATEMENT} and {:else} - using : instead of #.
  • We finish all logical statements with {/if}.
Last Updated 1648812185709

More Tips and Tricks for Svelte

Subscribe for Weekly Dev Tips

Subscribe to our weekly newsletter, to stay up to date with our latest web development and software engineering posts via email. You can opt out at any time.

Not a valid email