0
0
Svelteframework~15 mins

Else and else-if blocks in Svelte - Mini Project: Build & Apply

Choose your learning style9 modes available
Using else and else-if blocks in Svelte
📖 Scenario: You are building a simple Svelte component that shows a message based on the current hour of the day. This is like a digital greeting card that changes its message depending on the time.
🎯 Goal: Create a Svelte component that uses {#if}, {:else if}, and {:else} blocks to display different greetings for morning, afternoon, evening, and night.
📋 What You'll Learn
Create a variable hour with a number representing the current hour (0 to 23).
Create a variable morningStart set to 6 and afternoonStart set to 12.
Use {#if}, {:else if}, and {:else} blocks to show:
Good morning! if hour is between morningStart and afternoonStart - 1.
Good afternoon! if hour is between afternoonStart and 18.
Good evening! if hour is between 19 and 21.
Good night! for all other hours.
💡 Why This Matters
🌍 Real World
Time-based greetings are common in apps and websites to personalize user experience depending on the time of day.
💼 Career
Understanding conditional rendering in Svelte is essential for building interactive user interfaces that respond to data changes.
Progress0 / 4 steps
1
Set up the hour variable
Create a variable called hour and set it to 14 inside a <script> tag.
Svelte
Need a hint?

Use let hour = 14; inside the <script> tag.

2
Add morning and afternoon start variables
Inside the <script> tag, add two variables: morningStart set to 6 and afternoonStart set to 12.
Svelte
Need a hint?

Declare morningStart and afternoonStart with the given values.

3
Add if, else if, and else blocks for greetings
Below the <script> tag, use Svelte's {#if}, {:else if}, and {:else} blocks to show these messages based on hour: Good morning! if hour is between morningStart and afternoonStart - 1, Good afternoon! if hour is between afternoonStart and 18, Good evening! if hour is between 19 and 21, and Good night! for all other hours.
Svelte
Need a hint?

Use Svelte's {#if}, {:else if}, and {:else} blocks with the exact conditions and messages.

4
Complete the Svelte component
Make sure the entire Svelte component includes the <script> tag with variables and the conditional blocks below it exactly as described.
Svelte
Need a hint?

Review the full component to ensure all parts are included and correct.