Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 35 ยท Practice and Review

Svelte Practice Exercises with Solutions

Twelve Svelte 5 practice exercises on runes, bindings, each blocks, props, snippets, stores and SvelteKit, with hints and worked solutions you can check in your browser.

Reading about Svelte is not the same as writing it. These twelve exercises go from small to larger, covering runes, templates, components and SvelteKit. For each one: read the task, try it in a real project (npx sv create practice, or the online Svelte REPL at svelte.dev), peek at the hint only if you are stuck, and compare with the solution.

The Svelte compiler cannot run on this site, so solutions are read-only Svelte code. Where the logic can be separated from the framework, a runnable <TryIt> lets you check the idea in plain JavaScript.

Part 1: Reactivity

Exercise 1: Counter with limits

Build a counter with +, - and Reset buttons. The count must stay between 0 and 10, the minus button is disabled at 0 and the plus button at 10. Show "Max reached!" at 10.

Hint: disabled={count === 0}; compute messages with $derived.

HTML
<script>
  let count = $state(0);
  const atMax = $derived(count === 10);
</script>

<button onclick={() => count--} disabled={count === 0}>-</button>
<output>{count}</output>
<button onclick={() => count++} disabled={atMax}>+</button>
<button onclick={() => (count = 0)}>Reset</button>
{#if atMax}<p>Max reached!</p>{/if}

Exercise 2: Temperature converter

Two inputs, Celsius and Fahrenheit. Typing in one updates the other. Round to one decimal.

Hint: keep one source of truth (Celsius) and derive Fahrenheit; for two-way editing use function bindings (bind:value={getter, setter}).

HTML
<script>
  let celsius = $state(0);
  const round = (n) => Math.round(n * 10) / 10;
  const getF = () => round((celsius * 9) / 5 + 32);
  const setF = (f) => (celsius = round(((f - 32) * 5) / 9));
</script>

<label>ยฐC <input type="number" bind:value={celsius} /></label>
<label>ยฐF <input type="number" bind:value={getF, setF} /></label>

Check the conversion maths here:

JS Temperature maths

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 3: Password strength meter

An input shows a strength label (Weak, Okay, Strong) and a colored bar. Rules: length >= 8, has a digit, has an uppercase letter, has a symbol; strength = number of rules met.

Hint: a $derived for the score and another for the label.

HTML
<script>
  let password = $state('');
  const rules = [
    (p) => p.length >= 8,
    (p) => /\d/.test(p),
    (p) => /[A-Z]/.test(p),
    (p) => /[^A-Za-z0-9]/.test(p),
  ];
  const score = $derived(rules.filter((rule) => rule(password)).length);
  const label = $derived(['Too short', 'Weak', 'Okay', 'Good', 'Strong'][score]);
</script>

<input type="password" bind:value={password} aria-describedby="strength" />
<meter min="0" max="4" value={score}></meter>
<p id="strength">{label}</p>
JS Scoring passwords

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Part 2: Templates and components

Exercise 4: Filterable, sortable table

Given an array of countries (name, population), build a table with a text filter and a button that toggles sorting by population ascending/descending. Show "No matches" if the filter excludes everything.

Hint: a $derived.by that filters then sorts a copy (toSorted); key the each block by name.

HTML
<script>
  let { countries } = $props();
  let query = $state('');
  let descending = $state(true);

  const rows = $derived.by(() => {
    const q = query.toLowerCase();
    return countries
      .filter((c) => c.name.toLowerCase().includes(q))
      .toSorted((a, b) => (descending ? b.population - a.population : a.population - b.population));
  });
</script>

<input placeholder="Filter..." bind:value={query} />
<button onclick={() => (descending = !descending)}>
  Population {descending ? 'โ†“' : 'โ†‘'}
</button>

<table>
  <tbody>
    {#each rows as c (c.name)}
      <tr><td>{c.name}</td><td>{c.population.toLocaleString()}</td></tr>
    {:else}
      <tr><td colspan="2">No matches</td></tr>
    {/each}
  </tbody>
</table>
JS Filter and sort

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 5: Reusable Modal with snippets

Create Modal.svelte that takes open (bindable), a title, a children body and an optional footer snippet. Close on Escape and when the Close button is pressed.

HTML
<!-- Modal.svelte -->
<script>
  let { open = $bindable(false), title, children, footer } = $props();
</script>

<svelte:window onkeydown={(e) => e.key === 'Escape' && (open = false)} />

{#if open}
  <div role="dialog" aria-modal="true" aria-label={title}>
    <h2>{title}</h2>
    {@render children()}
    <div>
      {#if footer}{@render footer()}{/if}
      <button type="button" onclick={() => (open = false)}>Close</button>
    </div>
  </div>
{/if}
HTML
<!-- usage -->
<Modal bind:open={showHelp} title="Help">
  <p>Press Escape to close.</p>
  {#snippet footer()}<a href="/docs">Read more</a>{/snippet}
</Modal>

Exercise 6: Tabs component

Build <Tabs> with a list of {id, label} and a snippet that renders the active panel. Support arrow-key navigation between tabs and the right ARIA roles (tablist, tab, tabpanel).

Hint: the active tab has tabindex="0", others -1; Left/Right move the selection.

HTML
<script>
  let { tabs, panel } = $props();
  let active = $state(tabs[0].id);

  function onkeydown(e) {
    const i = tabs.findIndex((t) => t.id === active);
    if (e.key === 'ArrowRight') active = tabs[(i + 1) % tabs.length].id;
    if (e.key === 'ArrowLeft') active = tabs[(i - 1 + tabs.length) % tabs.length].id;
  }
</script>

<div role="tablist" {onkeydown}>
  {#each tabs as t (t.id)}
    <button role="tab" id="tab-{t.id}" aria-selected={active === t.id}
            aria-controls="panel-{t.id}" tabindex={active === t.id ? 0 : -1}
            onclick={() => (active = t.id)}>{t.label}</button>
  {/each}
</div>
<div role="tabpanel" id="panel-{active}" aria-labelledby="tab-{active}">
  {@render panel(active)}
</div>

Arrow wrap-around is the tricky part; check it:

JS Wrapping tab index

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Part 3: State beyond a component

Exercise 7: Shopping cart store

Write cart.svelte.js exporting a cart object with items, add(product), remove(id), a derived total and count. Adding the same product increases its quantity. Use it in two unrelated components.

JavaScript
class Cart {
  items = $state([]);
  total = $derived(this.items.reduce((s, i) => s + i.price * i.qty, 0));
  count = $derived(this.items.reduce((s, i) => s + i.qty, 0));

  add(product) {
    const found = this.items.find((i) => i.id === product.id);
    if (found) found.qty += 1;
    else this.items.push({ ...product, qty: 1 });
  }

  remove(id) {
    this.items = this.items.filter((i) => i.id !== id);
  }
}

export const cart = new Cart();
JS Cart rules

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 8: Context-based theme

Provide a theme ('light' or 'dark') from a layout with setContext, let any descendant read and toggle it with getContext, and apply it as a class on the wrapper.

HTML
<!-- ThemeProvider.svelte -->
<script>
  import { setContext } from 'svelte';
  let { children } = $props();

  const theme = $state({ mode: 'light' });
  setContext('theme', {
    get mode() { return theme.mode; },
    toggle() { theme.mode = theme.mode === 'light' ? 'dark' : 'light'; },
  });
</script>

<div class={theme.mode}>{@render children()}</div>
HTML
<!-- ThemeButton.svelte, anywhere below the provider -->
<script>
  import { getContext } from 'svelte';
  const theme = getContext('theme');
</script>

<button onclick={theme.toggle}>Switch to {theme.mode === 'light' ? 'dark' : 'light'}</button>

Part 4: Motion and SvelteKit

Exercise 9: Toast notifications

A store holds a list of toasts; a <Toasts> component shows them with fly in and fade out, and each one removes itself after 3 seconds. Use animate:flip so remaining toasts slide into place.

JavaScript
// toasts.svelte.js
let nextId = 1;
export const toasts = $state([]);

export function notify(text) {
  const toast = { id: nextId++, text };
  toasts.push(toast);
  setTimeout(() => {
    const i = toasts.findIndex((t) => t.id === toast.id);
    if (i !== -1) toasts.splice(i, 1);
  }, 3000);
}
HTML
<script>
  import { fly, fade } from 'svelte/transition';
  import { flip } from 'svelte/animate';
  import { toasts } from './toasts.svelte.js';
</script>

<div class="toasts" role="status" aria-live="polite">
  {#each toasts as t (t.id)}
    <div class="toast" in:fly={{ y: 20 }} out:fade animate:flip>{t.text}</div>
  {/each}
</div>

Exporting a $state array from a module is allowed as long as you mutate it (push, splice) rather than reassign the export.

JS Toast lifecycle with timers

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Exercise 10: A paginated list page in SvelteKit

Create /products?page=2 that shows 10 products per page with Previous/Next links. Read the page from the URL in a server load, return the slice and the total page count, and disable links at the ends.

JavaScript
// src/routes/products/+page.server.js
import { error } from '@sveltejs/kit';
import { listProducts } from '$lib/server/products';

const PAGE_SIZE = 10;

export async function load({ url }) {
  const page = Number(url.searchParams.get('page') ?? 1);
  if (!Number.isInteger(page) || page < 1) error(400, 'Invalid page');

  const { rows, total } = await listProducts({ limit: PAGE_SIZE, offset: (page - 1) * PAGE_SIZE });
  const pages = Math.max(1, Math.ceil(total / PAGE_SIZE));
  if (page > pages) error(404, 'No such page');

  return { rows, page, pages };
}
HTML
<script>
  let { data } = $props();
</script>

<ul>{#each data.rows as p (p.id)}<li>{p.name}</li>{/each}</ul>

<nav aria-label="Pages">
  {#if data.page > 1}<a href="?page={data.page - 1}">Previous</a>{/if}
  <span>Page {data.page} of {data.pages}</span>
  {#if data.page < data.pages}<a href="?page={data.page + 1}">Next</a>{/if}
</nav>

See Load Functions if the url and error parts feel unfamiliar.

Exercise 11: A contact form with an action

Add a contact form with name, email and message. Validate on the server with fail(), keep the user's input on errors, show a success message without a full reload using use:enhance.

Hint: return { success: true } on success and read it as form?.success. Revisit Form Actions.

JS Validate a contact message

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Combine everything: a SvelteKit app where a form action creates a short code for a URL (store in a Map or SQLite), /[code] redirects to the target with redirect(307, url), and /stats lists links with hit counts. Add a loading state with use:enhance, a 404 page for unknown codes, tests for the code generator and an accessibility pass.

Start with the pure logic, then wire it up:

JS Short-code generator and store

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In Exercise 2, why keep Celsius as the only source of truth?

    Store one value and compute the other; otherwise you need effects to sync, which are easy to get wrong.
  2. 2. Why use toSorted in the table exercise instead of sort?

    Never mutate state or props while computing derived values; toSorted works on a copy.
  3. 3. How do you pick a SvelteKit action in a form?

    Named actions are targeted with ?/name; the unnamed one is the default action.
  4. 4. What is the safest way to export shared reactive state from a module?

    Imports cannot be reassigned, so share an object (or class) and change its fields.

Summary

  • Practice by building: counters, forms, tables, modals, tabs, stores and SvelteKit pages cover most day-to-day Svelte.
  • Keep one source of truth, derive the rest, and mutate state instead of reassigning exports.
  • Separate pure logic from components so you can test it with plain JavaScript.
  • Finish with a capstone that uses routing, actions, load, redirects, tests and accessibility together.

Next: Svelte Interview Questions