Skip to main content

Part 1 / Logic / Else blocks

Since the two conditions — if user.loggedIn and if !user.loggedIn — are mutually exclusive, we can simplify this component slightly by using an else block:

App.svelte
{#if user.loggedIn}
	<button on:click={toggle}>
		Log out
	</button>
{:else}
	<button on:click={toggle}>
		Log in
	</button>
{/if}

A # character always indicates a block opening tag. A / character always indicates a block closing tag. A : character, as in {:else}, indicates a block continuation tag. Don't worry — you've already learned almost all the syntax Svelte adds to HTML.

Next: Else-if blocks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<script>
	let user = { loggedIn: false };
 
	function toggle() {
		user.loggedIn = !user.loggedIn;
	}
</script>
 
{#if user.loggedIn}
	<button on:click={toggle}>
		Log out
	</button>
{/if}
 
{#if !user.loggedIn}
	<button on:click={toggle}>
		Log in
	</button>
{/if}
 
initialising