Svelte Junior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. What is Svelte?

    Correct answer: A UI framework that compiles components into direct DOM updates

    Svelte does most of its work at build time. The output is small, framework-light code that changes exactly the DOM nodes that depend on changed state, without a virtual DOM.

  2. 2. What is SvelteKit?

    Correct answer: The official app framework for Svelte, built on Vite

    Svelte is the component layer; SvelteKit adds what a full app needs, similar to Next.js for React or Nuxt for Vue.

  3. 3. What is the recommended way to create a new SvelteKit project?

    Correct answer: npx sv create my-app

    sv is the official Svelte CLI. It scaffolds the project and can add integrations like TypeScript, ESLint, Vitest or Playwright.

  4. 4. What can a .svelte file contain?

    Correct answer: A <script> block, markup and a <style> block, all optional

    A component can have several top-level elements. There is also <script module>, which runs once when the module is evaluated rather than for each instance.

  5. 5. How is CSS in a component's <style> block applied by default?

    Correct answer: It is scoped to that component with a hash class

    For global rules use :global(...) or a :global { ... } block. Unused selectors produce a compiler warning and are removed from the output.

  6. 6. How do you output a JavaScript value in Svelte markup?

    <script>
      let name = "world";
    </script>
    
    <h1>Hello {name}!</h1>

    Correct answer: With curly braces: {name}

    Any JavaScript expression can go inside the braces. Text is escaped automatically, so it's safe from HTML injection.

  7. 7. What is the shorthand for <img src={src} alt={alt} />?

    Correct answer: <img {src} {alt} />

    When an attribute and a variable share a name, {name} is enough. You can also spread an object: <img {...attrs} />.

  8. 8. Does Svelte use a virtual DOM?

    Correct answer: No: the compiler generates direct DOM updates

    Reactivity in Svelte 5 is based on signals: the runtime knows exactly which template parts depend on which state.

  9. 9. What are runes in Svelte 5?

    Correct answer: Compiler keywords with a $ prefix that control reactivity

    Runes look like functions but are part of the language: they aren't imported and can't be assigned to variables or passed around.

  10. 10. How do you declare reactive state in Svelte 5?

    <script>
      let count = $state(0);
    </script>
    
    <button onclick={() => count++}>{count}</button>

    Correct answer: With $state(initialValue), used like a normal variable

    count is just a number, there is no .value or setter. Plain let declarations being reactive was Svelte 4 behaviour; in runes mode you need $state.

  11. 11. How do you declare a value computed from other state?

    let count = $state(2);
    let doubled = $derived(count * 2);

    Correct answer: With $derived(expression), recalculated on change

    Component code runs once on creation, so a plain let would keep the initial value. Updating state inside $effect for this is an anti-pattern.

  12. 12. What does $effect do?

    Correct answer: Runs code after mount and whenever its state changes

    Effects are for side effects: working with canvas, third-party libraries, subscriptions. They run in the browser only, not during SSR.

  13. 13. How does a component receive props in Svelte 5?

    <script>
      let { name, count = 0 } = $props();
    </script>

    Correct answer: With the $props() rune and destructuring

    export let is the Svelte 4 syntax. With $props() you can also collect the rest: let { a, ...rest } = $props().

  14. 14. Where can runes be used?

    Correct answer: In .svelte files and .svelte.js / .svelte.ts modules

    The .svelte.js extension tells the compiler to process runes, which allows reusable reactive logic outside components.

  15. 15. Is an object declared with $state deeply reactive?

    let todo = $state({ text: "Buy milk", done: false });
    todo.done = true;

    Correct answer: Yes: plain objects and arrays become reactive proxies

    Array methods like push also trigger updates. For large data that is only reassigned, $state.raw avoids the proxy overhead.

  16. 16. What does $inspect(value) do?

    Correct answer: Logs the value every time it changes, in development only

    It tracks deep changes too. In production builds $inspect is a no-op.

  17. 17. How do you render content conditionally?

    {#if user}
      <p>Hi, {user.name}</p>
    {:else}
      <a href="/login">Sign in</a>
    {/if}

    Correct answer: With {#if}, {:else if} and {:else} blocks

    Blocks start with #, continue with : and end with /.

  18. 18. How do you render a list?

    {#each todos as todo (todo.id)}
      <li>{todo.text}</li>
    {:else}
      <li>Nothing to do</li>
    {/each}

    Correct answer: With an {#each items as item (key)} block

    The expression in parentheses is the key. It helps Svelte insert and remove items precisely instead of updating existing DOM.

  19. 19. Why shouldn't you use the index as the key in {#each}?

    Correct answer: Indexes shift on reorder, so Svelte matches the wrong nodes

    Use a stable unique identifier like item.id. The index is available as the second variable: {#each items as item, i (item.id)}.

  20. 20. What does the {#await} block do?

    {#await promise}
      <p>Loading…</p>
    {:then user}
      <p>{user.name}</p>
    {:catch error}
      <p>{error.message}</p>
    {/await}

    Correct answer: Shows different content for each state of a promise

    If the promise changes, the block switches back to the pending state. {:catch} and the pending part are optional.

  21. 21. How do you handle a click in Svelte 5?

    Correct answer: <button onclick={handleClick}>

    In Svelte 5 events are plain attributes starting with on. The on:click directive is the legacy Svelte 4 syntax.

  22. 22. How do you prevent a form's default submission in Svelte 5?

    Correct answer: Call event.preventDefault() in the onsubmit handler

    Event modifiers like |preventDefault belong to the legacy on: directive. With event attributes you handle it in the function.

  23. 23. What does bind:value do?

    <script>
      let name = $state("");
    </script>
    
    <input bind:value={name} />
    <p>Hello {name}</p>

    Correct answer: Creates a two-way binding between name and the input

    For checkboxes there is bind:checked, for radio groups bind:group, for <input type="number"> the value is converted to a number.

  24. 24. How do you get a reference to a DOM element?

    <script>
      let canvas;
    </script>
    
    <canvas bind:this={canvas}></canvas>

    Correct answer: With bind:this, set after the element mounts

    The value is undefined until mount, so use it in $effect, onMount or event handlers.

  25. 25. What is the risk of {@html content}?

    Correct answer: It skips escaping, so untrusted content can cause XSS

    Only use it with trusted or sanitized HTML. Scoped styles also don't apply to markup inserted this way.

  26. 26. How can you pass several classes conditionally in Svelte 5?

    <div class={["card", { active: isActive, disabled }]}></div>

    Correct answer: Pass an array or object to class, like clsx

    Objects and arrays in class are supported since Svelte 5.16. The class: directive still works but is no longer the recommended approach.

  27. 27. What does the style: directive do?

    <p style:color={color} style:--columns={columns}>...</p>

    Correct answer: Sets a single inline style or CSS variable

    Setting a custom property is a clean way to use JavaScript values in the component's CSS.

  28. 28. How do you use one component inside another?

    <script>
      import Button from "./Button.svelte";
    </script>
    
    <Button label="Save" />

    Correct answer: Import it and use it as a tag with a capitalized name

    Component names start with a capital letter so the compiler can tell them from HTML elements.

  29. 29. How does a component render content passed between its tags in Svelte 5?

    <!-- Card.svelte -->
    <script>
      let { children } = $props();
    </script>
    
    <div class="card">{@render children?.()}</div>

    Correct answer: Through the children prop and {@render children()}

    <slot> is the Svelte 4 mechanism. The optional call children?.() avoids an error when nothing was passed.

  30. 30. What is a snippet?

    {#snippet row(item)}
      <tr><td>{item.name}</td></tr>
    {/snippet}
    
    {@render row(first)}

    Correct answer: A reusable chunk of markup with parameters

    Snippets replace named slots: a component can accept header, row and other snippet props.

  31. 31. How does a child component tell its parent that something happened in Svelte 5?

    <!-- Child.svelte -->
    <script>
      let { onsave } = $props();
    </script>
    
    <button onclick={() => onsave("data")}>Save</button>

    Correct answer: By calling a callback function passed as a prop

    createEventDispatcher is deprecated in Svelte 5. Callback props are simpler and fully typed.

  32. 32. How do you allow a parent to use bind:value on your component's prop?

    <script>
      let { value = $bindable("") } = $props();
    </script>
    
    <input bind:value />

    Correct answer: Mark the prop with $bindable()

    Props flow down by default. $bindable explicitly allows two-way binding, which keeps data flow understandable.

  33. 33. Should a component mutate a prop object it received (not marked $bindable)?

    Correct answer: No: the parent owns it, so use callbacks or $bindable

    Mutating someone else's state makes data flow hard to follow. Let the owner change it.

  34. 34. How do you render a component chosen at runtime in Svelte 5?

    <script>
      let { Component } = $props();
    </script>
    
    <Component />

    Correct answer: Use the variable holding the component directly as a tag

    Components are dynamic in runes mode, so <svelte:component> is no longer needed.

  35. 35. How can a parent style an element inside a child component without breaking scoping?

    <!-- Parent.svelte -->
    <Child --accent="tomato" />

    Correct answer: Pass a CSS custom property that the child reads

    Custom properties keep the child in control of its styles. :global is a fallback for third-party components.

  36. 36. When does onMount run?

    Correct answer: After the component is first mounted in the DOM, in the browser only

    A function returned from onMount runs when the component is destroyed. It doesn't run during SSR.

  37. 37. How do you clean up a timer created in $effect?

    $effect(() => {
      const id = setInterval(tick, 1000);
      return () => clearInterval(id);
    });

    Correct answer: Return a teardown function from the effect

    The same applies to subscriptions, observers and event listeners.

  38. 38. What does tick() return?

    Correct answer: A promise that resolves once the DOM is updated

    await tick() is useful when you need to read the updated DOM right after changing state, for example to move focus.

  39. 39. How do you animate an element appearing and disappearing?

    <script>
      import { fade } from "svelte/transition";
      let visible = $state(true);
    </script>
    
    {#if visible}
      <p transition:fade>Hello</p>
    {/if}

    Correct answer: With transition: and a function from svelte/transition

    in: and out: set separate intro and outro transitions. Built-ins include fade, fly, slide, scale, blur, draw.

  40. 40. What does animate:flip do in a keyed {#each}?

    Correct answer: Smoothly moves items to their new positions

    FLIP (First, Last, Invert, Play) computes the movement. animate: works only on direct children of a keyed each block.

  41. 41. What is context in Svelte for?

    Correct answer: Passing values to descendants without prop drilling

    Context is scoped to the component tree, which also keeps it safe from leaking between users during SSR.

  42. 42. When must setContext / getContext be called?

    Correct answer: During component initialization, at the top of <script>

    Context is tied to the component being created. Since Svelte 5.40, createContext gives a typed [get, set] pair.

  43. 43. What is a store in Svelte?

    Correct answer: An object with a subscribe method (the store contract)

    In Svelte 5 most cases are covered by runes, but stores are still handy for complex async streams and are fully supported.

  44. 44. What does the $ prefix do with a store in a component?

    <script>
      import { count } from "./stores.js";
    </script>
    
    <p>{$count}</p>

    Correct answer: Subscribes to the store and reads its current value

    Assigning $count = 1 calls count.set(1) on a writable store. The store must be declared at the top level of the component.

  45. 45. How do you share reactive state between components without stores in Svelte 5?

    // counter.svelte.js
    export const counter = $state({ value: 0 });

    Correct answer: Export a $state object from a .svelte.js module

    Exporting a reassigned primitive (export let count = $state(0)) doesn't work, because importers get a value, not a live binding; mutate an object or export getter functions.

  46. 46. How do you add a listener to window from a component?

    Correct answer: <svelte:window onkeydown={handleKey} />

    Svelte adds and removes the listener with the component lifecycle and it's safe during SSR. You can also bind innerWidth, scrollY and similar values.

  47. 47. How do you set the page title from a component?

    Correct answer: <svelte:head><title>Settings</title></svelte:head>

    Content of <svelte:head> is inserted into document.head and is also rendered during SSR, which matters for SEO.

  48. 48. What does <svelte:element this={tag}> do?

    Correct answer: Renders an element whose tag is known only at runtime

    Useful for headings with a configurable level (h1-h6) or a button/a switch. If this is falsy, nothing is rendered.

  49. 49. How are routes defined in SvelteKit?

    Correct answer: By the folder structure inside src/routes

    src/routes/about/+page.svelte becomes /about. Files with a + prefix have special meaning for the router.

  50. 50. How do you create a route with a parameter, like /blog/hello-world?

    Correct answer: A [slug] folder: blog/[slug]/+page.svelte

    The value is available as params.slug in load and in page.params. [...rest] matches several segments, [[optional]] an optional one.

  51. 51. What is +layout.svelte for?

    Correct answer: UI shared by all pages in its folder and subfolders

    Layouts nest: the root layout wraps everything, a layout in settings/ wraps only settings pages.

  52. 52. How does a page get data from its load function?

    // +page.js
    export function load({ params }) {
      return { post: getPost(params.slug) };
    }
    
    <!-- +page.svelte -->
    <script>
      let { data } = $props();
    </script>
    <h1>{data.post.title}</h1>

    Correct answer: What load returns arrives as the data prop

    Data from layouts' load functions is merged into data as well.

  53. 53. What is the difference between +page.js and +page.server.js?

    Correct answer: +page.server.js runs only on the server, +page.js on both

    A universal load in +page.js runs during SSR and then in the browser on client-side navigation.

  54. 54. What file creates an API endpoint in SvelteKit?

    // src/routes/api/hello/+server.js
    export function GET() {
      return Response.json({ message: "Hello" });
    }

    Correct answer: +server.js exporting HTTP method functions

    Handlers receive a request event and return a standard Response. SvelteKit is built on web standards like Request, Response and FormData.

  55. 55. How do you show a 404 page from load when a post doesn't exist?

    import { error } from "@sveltejs/kit";
    
    export async function load({ params }) {
      const post = await db.getPost(params.slug);
      if (!post) error(404, "Not found");
      return { post };
    }

    Correct answer: Call error(404, ...) from @sveltejs/kit

    Expected errors created with error() show their message. Unexpected exceptions are hidden from users and go to handleError.

  56. 56. What are form actions in SvelteKit?

    Correct answer: Server functions that handle <form method="POST">

    Forms work even without JavaScript. With use:enhance the submission happens without a full page reload.

  57. 57. How do you navigate between pages in SvelteKit?

    Correct answer: With a regular <a href="/about"> link

    Plain links keep the app accessible and working without JavaScript. goto() from $app/navigation is for programmatic navigation.

  58. 58. What are SvelteKit adapters?

    Correct answer: Plugins that prepare the build for a specific platform

    adapter-auto detects the platform; adapter-static produces a static site; adapter-node a standalone Node server.

  59. 59. What does export const prerender = true in +page.js do?

    Correct answer: Generates the page as static HTML at build time

    Prerendering suits pages that are the same for everyone, like docs or a blog. Other page options are ssr and csr.

  60. 60. What does this code print when the button is clicked twice?

    <script>
      let count = $state(0);
      let doubled = count * 2;
    </script>
    
    <button onclick={() => count++}>{count} / {doubled}</button>

    Correct answer: 2 / 0: doubled isn't reactive

    Script code runs once. To keep doubled in sync use $derived(count * 2).

  61. 61. What happens with reactivity here?

    let user = $state({ name: "Ann" });
    let { name } = user;
    user.name = "Bob";
    // name === ?

    Correct answer: name stays "Ann": destructuring copies it

    Like in plain JavaScript, destructured values aren't live. Read user.name or use $derived.

  62. 62. What does {@const} do?

    {#each boxes as box}
      {@const area = box.width * box.height}
      <p>{box.width} × {box.height} = {area}</p>
    {/each}

    Correct answer: Declares a local constant inside a block of markup

    It's allowed only as the immediate child of blocks like {#each}, {#if}, {:then}, {#snippet} or a component.

  63. 63. What does {#key value} do?

    Correct answer: Destroys and recreates its contents on change

    Useful to replay a transition on change. It is expensive, so don't use it just to re-run logic; $derived is usually better.

  64. 64. How do you use TypeScript in a Svelte component?

    <script lang="ts">
      interface Props { title: string; count?: number }
      let { title, count = 0 }: Props = $props();
    </script>

    Correct answer: Add lang="ts" to the <script> tag

    sv check (svelte-check) type-checks templates as well.

  65. 65. Which Svelte version introduced runes?

    Correct answer: Svelte 5

    Svelte 5 still runs most Svelte 4 syntax in components that don't use runes (legacy mode), which allows gradual migration.

  66. 66. Which syntax is legacy (Svelte 4) and should be avoided in new code?

    Correct answer: export let, $:, on:click and <slot>

    Their replacements: $props, $derived/$effect, onclick and snippets with {@render}.

  67. 67. How do you make a checkbox group bound to an array?

    <script>
      let toppings = $state([]);
    </script>
    
    <input type="checkbox" value="cheese" bind:group={toppings} />
    <input type="checkbox" value="ham" bind:group={toppings} />

    Correct answer: bind:group on each checkbox

    For radio buttons bind:group holds a single value instead of an array.

  68. 68. What does the use: directive (action) receive?

    <script>
      function tooltip(node, text) {
        // set up
        return { destroy() { /* clean up */ } };
      }
    </script>
    
    <button use:tooltip={"Save changes"}>Save</button>

    Correct answer: The DOM element and an optional parameter

    Actions are still supported, but Svelte 5.29+ recommends attachments ({@attach}), which are more flexible and react to state changes.

  69. 69. How do you check Svelte types and templates from the command line?

    Correct answer: npx sv check

    tsc alone doesn't understand .svelte files. sv check runs svelte-check, which reports type errors and compiler warnings like accessibility hints.

  70. 70. What does the Svelte compiler warn about with <div onclick={...}>?

    Correct answer: Accessibility: it should be a <button> or have a role

    Svelte includes a11y checks at compile time, which catch many problems early.

  71. 71. What does $state.snapshot(value) return?

    Correct answer: A plain, non-reactive copy of a state proxy

    Some APIs, like structuredClone, don't work with proxies; the snapshot solves that.

  72. 72. How do you read the current URL or route params in a SvelteKit component?

    <script>
      import { page } from "$app/state";
    </script>
    
    <p>{page.url.pathname}</p>

    Correct answer: Import page from $app/state

    $app/state gives reactive values. $app/stores was the old store-based API; it was deprecated and removed in SvelteKit 3.

  73. 73. Why are Svelte bundles often small?

    Correct answer: The compiler outputs only the code a component needs

    There is no big framework runtime with a virtual DOM to ship. Bundle size still grows with the number of components.

  74. 74. Where do static files like favicon.png go in a SvelteKit project?

    Correct answer: In the static/ folder at the project root

    Files imported from code (e.g. images in src/) are processed by Vite and get hashed names for caching.

  75. 75. Which file defines the HTML shell for every SvelteKit page?

    Correct answer: src/app.html

    It contains placeholders like %sveltekit.head% and %sveltekit.body% where SvelteKit inserts content.

  76. 76. What does <svelte:boundary> do?

    Correct answer: Catches render errors and shows a failed snippet

    Errors in event handlers or setTimeout callbacks are not caught. With async Svelte it can also show a pending snippet.