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. 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. 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. What is the recommended way to create a new SvelteKit project?
Correct answer:
npx sv create my-appsvis the official Svelte CLI. It scaffolds the project and can add integrations like TypeScript, ESLint, Vitest or Playwright.4. What can a
.sveltefile contain?Correct answer: A
<script>block, markup and a<style>block, all optionalA 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. 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. 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. 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. 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. What are runes in Svelte 5?
Correct answer: Compiler keywords with a
$prefix that control reactivityRunes look like functions but are part of the language: they aren't imported and can't be assigned to variables or passed around.
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 variablecountis just a number, there is no.valueor setter. Plainletdeclarations being reactive was Svelte 4 behaviour; in runes mode you need$state.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 changeComponent code runs once on creation, so a plain
letwould keep the initial value. Updating state inside$effectfor this is an anti-pattern.12. What does
$effectdo?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. How does a component receive props in Svelte 5?
<script> let { name, count = 0 } = $props(); </script>Correct answer: With the
$props()rune and destructuringexport letis the Svelte 4 syntax. With$props()you can also collect the rest:let { a, ...rest } = $props().14. Where can runes be used?
Correct answer: In
.sveltefiles and.svelte.js/.svelte.tsmodulesThe
.svelte.jsextension tells the compiler to process runes, which allows reusable reactive logic outside components.15. Is an object declared with
$statedeeply 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
pushalso trigger updates. For large data that is only reassigned,$state.rawavoids the proxy overhead.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
$inspectis a no-op.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}blocksBlocks start with
#, continue with:and end with/.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)}blockThe expression in parentheses is the key. It helps Svelte insert and remove items precisely instead of updating existing DOM.
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. 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. How do you handle a click in Svelte 5?
Correct answer:
<button onclick={handleClick}>In Svelte 5 events are plain attributes starting with
on. Theon:clickdirective is the legacy Svelte 4 syntax.22. How do you prevent a form's default submission in Svelte 5?
Correct answer: Call
event.preventDefault()in theonsubmithandlerEvent modifiers like
|preventDefaultbelong to the legacyon:directive. With event attributes you handle it in the function.23. What does
bind:valuedo?<script> let name = $state(""); </script> <input bind:value={name} /> <p>Hello {name}</p>Correct answer: Creates a two-way binding between
nameand the inputFor checkboxes there is
bind:checked, for radio groupsbind:group, for<input type="number">the value is converted to a number.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 mountsThe value is
undefineduntil mount, so use it in$effect,onMountor event handlers.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. 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, likeclsxObjects and arrays in
classare supported since Svelte 5.16. Theclass:directive still works but is no longer the recommended approach.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. 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. 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
childrenprop and{@render children()}<slot>is the Svelte 4 mechanism. The optional callchildren?.()avoids an error when nothing was passed.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,rowand other snippet props.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
createEventDispatcheris deprecated in Svelte 5. Callback props are simpler and fully typed.32. How do you allow a parent to use
bind:valueon 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.
$bindableexplicitly allows two-way binding, which keeps data flow understandable.33. Should a component mutate a prop object it received (not marked
$bindable)?Correct answer: No: the parent owns it, so use callbacks or
$bindableMutating someone else's state makes data flow hard to follow. Let the owner change it.
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. 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.
:globalis a fallback for third-party components.36. When does
onMountrun?Correct answer: After the component is first mounted in the DOM, in the browser only
A function returned from
onMountruns when the component is destroyed. It doesn't run during SSR.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. 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. 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 fromsvelte/transitionin:andout:set separate intro and outro transitions. Built-ins includefade,fly,slide,scale,blur,draw.40. What does
animate:flipdo 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. 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. When must
setContext/getContextbe called?Correct answer: During component initialization, at the top of
<script>Context is tied to the component being created. Since Svelte 5.40,
createContextgives a typed[get, set]pair.43. What is a store in Svelte?
Correct answer: An object with a
subscribemethod (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. 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 = 1callscount.set(1)on a writable store. The store must be declared at the top level of the component.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
$stateobject from a.svelte.jsmoduleExporting 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. How do you add a listener to
windowfrom 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,scrollYand similar values.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 intodocument.headand is also rendered during SSR, which matters for SEO.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 abutton/aswitch. Ifthisis falsy, nothing is rendered.49. How are routes defined in SvelteKit?
Correct answer: By the folder structure inside
src/routessrc/routes/about/+page.sveltebecomes/about. Files with a+prefix have special meaning for the router.50. How do you create a route with a parameter, like
/blog/hello-world?Correct answer: A
[slug]folder:blog/[slug]/+page.svelteThe value is available as
params.sluginloadand inpage.params.[...rest]matches several segments,[[optional]]an optional one.51. What is
+layout.sveltefor?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. How does a page get data from its
loadfunction?// +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
loadreturns arrives as thedatapropData from layouts'
loadfunctions is merged intodataas well.53. What is the difference between
+page.jsand+page.server.js?Correct answer:
+page.server.jsruns only on the server,+page.json bothA universal load in
+page.jsruns during SSR and then in the browser on client-side navigation.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.jsexporting HTTP method functionsHandlers receive a request event and return a standard
Response. SvelteKit is built on web standards likeRequest,ResponseandFormData.55. How do you show a 404 page from
loadwhen 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/kitExpected errors created with
error()show their message. Unexpected exceptions are hidden from users and go tohandleError.56. What are form actions in SvelteKit?
Correct answer: Server functions that handle
<form method="POST">Forms work even without JavaScript. With
use:enhancethe submission happens without a full page reload.57. How do you navigate between pages in SvelteKit?
Correct answer: With a regular
<a href="/about">linkPlain links keep the app accessible and working without JavaScript.
goto()from$app/navigationis for programmatic navigation.58. What are SvelteKit adapters?
Correct answer: Plugins that prepare the build for a specific platform
adapter-autodetects the platform;adapter-staticproduces a static site;adapter-nodea standalone Node server.59. What does
export const prerender = truein+page.jsdo?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
ssrandcsr.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:doubledisn't reactiveScript code runs once. To keep
doubledin sync use$derived(count * 2).61. What happens with reactivity here?
let user = $state({ name: "Ann" }); let { name } = user; user.name = "Bob"; // name === ?Correct answer:
namestays "Ann": destructuring copies itLike in plain JavaScript, destructured values aren't live. Read
user.nameor use$derived.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. 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;
$derivedis usually better.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>tagsv check(svelte-check) type-checks templates as well.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. Which syntax is legacy (Svelte 4) and should be avoided in new code?
Correct answer:
export let,$:,on:clickand<slot>Their replacements:
$props,$derived/$effect,onclickand snippets with{@render}.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:groupon each checkboxFor radio buttons
bind:groupholds a single value instead of an array.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. How do you check Svelte types and templates from the command line?
Correct answer:
npx sv checktscalone doesn't understand.sveltefiles.sv checkruns svelte-check, which reports type errors and compiler warnings like accessibility hints.70. What does the Svelte compiler warn about with
<div onclick={...}>?Correct answer: Accessibility: it should be a
<button>or have a roleSvelte includes a11y checks at compile time, which catch many problems early.
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. 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
pagefrom$app/state$app/stategives reactive values.$app/storeswas the old store-based API; it was deprecated and removed in SvelteKit 3.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. Where do static files like
favicon.pnggo in a SvelteKit project?Correct answer: In the
static/folder at the project rootFiles imported from code (e.g. images in
src/) are processed by Vite and get hashed names for caching.75. Which file defines the HTML shell for every SvelteKit page?
Correct answer:
src/app.htmlIt contains placeholders like
%sveltekit.head%and%sveltekit.body%where SvelteKit inserts content.76. What does
<svelte:boundary>do?Correct answer: Catches render errors and shows a
failedsnippetErrors in event handlers or
setTimeoutcallbacks are not caught. With async Svelte it can also show apendingsnippet.