issue 117apr 27mmxxvi
est. 2017
Sun, 27 Apr 2026
vol. IX · no. 117
PapersAdda
placement intelligence, since 2017
640+ briefs · 24 campuses · by reservation
verified offers · sourced from r/developersIndia
razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1
section: Interview Questions / interview questions
08 Jun 2026
placement brief / Interview Questions / interview questions / 08 Jun 2026

Svelte Interview Questions and Answers 2026

Svelte takes a fundamentally different approach from React and Vue by shifting work to compile time rather than runtime. Candidates report that Svelte's...

Aditya Sharma
Aditya's Edit

PapersAdda 2026 Placement Cycle

By Aditya Sharma·Founder & Editor, PapersAdda

What changed in 2026 drives

Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.

What I'd actually study for this

  • 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
  • 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
  • 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
  • 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken

Where most candidates trip up

The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.

Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.

Svelte takes a fundamentally different approach from React and Vue by shifting work to compile time rather than runtime. Candidates report that Svelte's compile-time reactivity model, stores, SvelteKit routing and SSR, and the Svelte 5 runes system are the most frequently tested topics in frontend interviews. This guide covers 40 questions from basics to advanced patterns. Always confirm the specific Svelte version in use at your target company on their official careers portal.

Table of Contents

  1. Svelte Fundamentals
  2. Reactivity and State
  3. Components and Props
  4. Stores
  5. SvelteKit
  6. Svelte 5 Runes
  7. Performance and Advanced Patterns
  8. 5-Question Mock Test
  9. Frequently Asked Questions

Svelte Fundamentals

Q1. What is Svelte and how does it differ from React/Vue? Easy

Svelte is a compiler that converts component code to vanilla JavaScript at build time. Unlike React and Vue, which ship a runtime library to the browser and use a virtual DOM for reconciliation, Svelte generates highly targeted imperative DOM manipulation code. There is no virtual DOM, no diffing algorithm, and no runtime framework overhead in the browser bundle.

FeatureSvelteReactVue 3
ApproachCompilerRuntime VDOMRuntime VDOM
Bundle sizeSmallestLarger (React + ReactDOM)Medium
ReactivityCompile-time assignmentsHooks, explicit stateProxy-based
Templates.svelte filesJSXSFC .vue files
Learning curveLow (HTML-first)MediumMedium
State managementBuilt-in storesExternal (Redux, Zustand)Pinia (official)

Q2. What is the structure of a Svelte component? Easy

A Svelte component is a .svelte file with three optional sections:

<script>
  // Component logic, imports, reactive declarations
  import { onMount } from 'svelte'
  import ChildComponent from './Child.svelte'

  let count = 0
  let name = 'World'

  $: doubled = count * 2  // reactive declaration

  onMount(() => {
    console.log('Component mounted')
  })

  function increment() {
    count++
  }
</script>


<main>
  <h1>Hello {name}!</h1>
  <p>Count: {count}, Doubled: {doubled}</p>
  <button on:click={increment}>Increment</button>
  <ChildComponent {name} />
</main>

<style>
  /* Scoped CSS - only applies to this component */
  main {
    max-width: 800px;
    margin: 0 auto;
  }
  h1 {
    color: #ff3e00; /* Svelte orange */
  }
</style>

Q3. How does Svelte's compile-time reactivity work? Medium

The Svelte compiler analyzes which variables are assigned to in <script> blocks. Any variable that is assigned (not just mutated) generates reactive update code. When you write count = count + 1, the compiler generates DOM update calls alongside the assignment.

The compiled output for let count = 0 with a binding to the DOM is approximately:

// Compiled output (simplified)
let count = 0;
// ...
function increment() {
  count++;
  $$invalidate(0, count); // compiler-generated: triggers DOM update
}

This means you MUST use assignment to trigger reactivity. Array mutations like .push() are not tracked unless followed by a self-assignment: arr.push(item); arr = arr.

Q4. What is the $: label in Svelte 4? Easy

The $: label marks a reactive statement or declaration. It re-runs whenever any variable it depends on changes.

<script>
  let count = 0
  let name = 'Svelte'

  // Reactive declaration: recomputes when count changes
  $: doubled = count * 2

  // Reactive statement: runs as a side effect
  $: console.log('count is now', count)

  // Reactive block
  $: {
    document.title = `${name} - Count: ${count}`
    if (count > 10) console.log('High count!')
  }

  // Reactive if
  $: if (count >= 5) {
    alert('Count reached 5!')
  }
</script>

$: statements are ordered topologically; if one depends on another, Svelte resolves the correct execution order.

Q5. How does two-way binding work in Svelte? Easy

Svelte uses bind: directives for two-way data binding.

<script>
  let name = ''
  let checked = false
  let selected = ''
  let fileList

  // Group binding for checkboxes
  let colors = []
</script>

<input bind:value={name} placeholder="Name" />
<input type="checkbox" bind:checked={checked} />
<select bind:value={selected}>
  <option value="a">A</option>
  <option value="b">B</option>
</select>
<input type="file" bind:files={fileList} />


<input type="checkbox" bind:group={colors} value="red" />
<input type="checkbox" bind:group={colors} value="blue" />


<CustomInput bind:value={name} />

Component bind:value requires the child to export value as a prop and fire updates by assigning to it.


Reactivity and State

Q6. Predict the output: Medium

// In a Svelte component
let items = [1, 2, 3]

function addItem() {
  items.push(4)
  // Is the UI updated?
}

function addItemCorrect() {
  items = [...items, 4]
  // Is the UI updated?
}

Output / Explanation:

addItem(): the UI is NOT updated. Array.push mutates the array in place without triggering an assignment. Svelte only detects reactivity through assignment.

addItemCorrect(): the UI IS updated. The spread creates a new array and assigns it to items, which the compiler detects as an invalidation.

Alternative fix: items.push(4); items = items (self-assignment triggers reactivity).

Q7. How do you handle async data fetching in Svelte? Medium

Svelte provides the {#await} block for template-level async handling, and onMount for lifecycle-based fetching.

<script>
  import { onMount } from 'svelte'

  // Method 1: {#await} block (promise in script)
  const promise = fetch('/api/users').then(r => r.json())

  // Method 2: onMount
  let users = []
  let loading = true
  let error = null

  onMount(async () => {
    try {
      const res = await fetch('/api/users')
      users = await res.json()
    } catch (e) {
      error = e.message
    } finally {
      loading = false
    }
  })
</script>


{#await promise}
  <p>Loading...</p>
{:then users}
  {#each users as user}
    <p>{user.name}</p>
  {/each}
{:catch error}
  <p>Error: {error.message}</p>
{/await}


{#if loading}<p>Loading...</p>
{:else if error}<p>Error: {error}</p>
{:else}
  {#each users as user}<p>{user.name}</p>{/each}
{/if}

Q8. What is the each block's key and why is it important? Medium

The {#each} key tells Svelte how to match items across re-renders, enabling efficient DOM reuse and preserving component state.


{#each items as item}
  <TodoItem {item} />
{/each}


{#each items as item (item.id)}
  <TodoItem {item} />
{/each}


{#each users as { id, name }, i (id)}
  <p>{i + 1}. {name}</p>
{:else}
  <p>No users found.</p>
{/each}

Without a key, if you reorder items, Svelte updates props in-place which is efficient for simple lists but loses component-internal state (form input values, animations).


Components and Props

Q9. How do you declare and use props in Svelte? Easy

Props are declared with export let in the component's script block.


<script>
  // Required prop (no default)
  export let name

  // Optional prop with default
  export let count = 0
  export let color = 'blue'
  export let items = []

  // Readonly export (for parent binding)
  export let value = ''
</script>

<div style="color: {color}">
  {name}: {count}
</div>


<script>
  import Child from './Child.svelte'
  let items = ['a', 'b']
</script>

<Child name="Example" count={42} {items} color="red" />

Q10. What is the difference between on:event and createEventDispatcher? Medium

createEventDispatcher creates custom events that bubble through the component tree. on:event listens to both DOM events and custom events.


<script>
  import { createEventDispatcher } from 'svelte'

  const dispatch = createEventDispatcher()

  function handleClick() {
    dispatch('message', {
      text: 'Hello from child',
      timestamp: Date.now()
    })
  }

  function handleError() {
    dispatch('error', new Error('Something went wrong'))
  }
</script>

<button on:click={handleClick}>Send Message</button>


<script>
  import Child from './Child.svelte'

  function onMessage(event) {
    console.log(event.detail.text) // 'Hello from child'
  }
</script>

<Child on:message={onMessage} on:error={(e) => alert(e.detail.message)} />


<Child on:message />

Note: in Svelte 5, custom events are replaced by callback props (onevent naming convention).

Q11. How do slots work in Svelte? Medium

Slots allow parent components to inject content into a child component.


<div class="card">
  <header>
    <slot name="header">Default header</slot>
  </header>
  <main>
    <slot />  
  </main>
  <footer>
    <slot name="footer" />
  </footer>
</div>


<Card>
  <svelte:fragment slot="header">
    <h2>My Title</h2>
  </svelte:fragment>
  <p>Card content goes here.</p>
  <span slot="footer">Footer text</span>
</Card>



<ul>
  {#each items as item}
    <li><slot {item} /></li>
  {/each}
</ul>


<List {items} let:item>
  <strong>{item.name}</strong> - {item.value}
</List>

Stores

Q12. What are the three types of Svelte stores? Easy

import { writable, readable, derived } from 'svelte/store'

// writable: read + write
const count = writable(0)
count.set(5)
count.update(n => n + 1)
count.subscribe(value => console.log(value))

// readable: read-only (external data source)
const time = readable(new Date(), function start(set) {
  const interval = setInterval(() => set(new Date()), 1000)
  return function stop() { clearInterval(interval) }
})

// derived: computed from other stores
const doubled = derived(count, $count => $count * 2)

// Derived from multiple stores
const combined = derived(
  [count, time],
  ([$count, $time]) => `Count: ${$count} at ${$time.toTimeString()}`
)

Q13. How does the $ auto-subscription syntax work? Easy

Prefixing a store with $ inside a .svelte file automatically subscribes and unsubscribes. Svelte adds subscribe/unsubscribe calls in the compiled output via onMount/onDestroy.

<script>
  import { count, doubled } from './stores'

  // Manual subscription (verbose, leak risk if not unsubscribed)
  let countValue
  const unsubscribe = count.subscribe(v => countValue = v)
  import { onDestroy } from 'svelte'
  onDestroy(unsubscribe)

  // Auto-subscription (preferred): Svelte handles cleanup
  // Just use $count directly in script or template
</script>


<p>Count: {$count}</p>
<p>Doubled: {$doubled}</p>


<script>
  $: console.log('count changed:', $count) // reactive to store changes
</script>


<button on:click={() => $count++}>Increment</button>

The $store = value syntax calls store.set(value).

Q14. How do you build a custom store? Advanced

Any object with a subscribe method conforming to the store contract is a valid Svelte store. This enables building domain-specific stores with encapsulated logic.

// stores/cart.js
import { writable, derived } from 'svelte/store'

function createCart() {
  const { subscribe, set, update } = writable([])

  return {
    subscribe,
    addItem: (item) => update(items => {
      const existing = items.find(i => i.id === item.id)
      if (existing) {
        return items.map(i => i.id === item.id
          ? { ...i, quantity: i.quantity + 1 }
          : i
        )
      }
      return [...items, { ...item, quantity: 1 }]
    }),
    removeItem: (id) => update(items => items.filter(i => i.id !== id)),
    clear: () => set([])
  }
}

export const cart = createCart()

export const cartTotal = derived(cart, $cart =>
  $cart.reduce((sum, item) => sum + item.price * item.quantity, 0)
)
export const cartCount = derived(cart, $cart =>
  $cart.reduce((sum, item) => sum + item.quantity, 0)
)

SvelteKit

Q15. What is SvelteKit and how does its routing work? Easy

SvelteKit is the official full-stack framework built on Svelte. It provides file-based routing, SSR, SSG, form actions, server-side endpoints, and adapters for various deployment targets.

Routes are defined by the file structure in src/routes/:

src/routes/
  +page.svelte          → /
  +layout.svelte        → wraps all pages
  +error.svelte         → error page
  about/
    +page.svelte        → /about
  blog/
    +page.svelte        → /blog
    +page.server.js     → server-side load for /blog
    [slug]/
      +page.svelte      → /blog/:slug (dynamic)
      +page.server.js   → server load for individual post
  api/
    users/
      +server.js        → /api/users REST endpoint

Q16. What are load functions in SvelteKit? Medium

Load functions fetch data before rendering. +page.server.js runs on the server only; +page.js runs on both server and client (isomorphic).

// src/routes/blog/[slug]/+page.server.js
export async function load({ params, fetch, locals, cookies }) {
  const post = await db.getPost(params.slug)

  if (!post) {
    throw error(404, 'Post not found')
  }

  return {
    post,
    user: locals.user // set by hooks.server.js
  }
}

// src/routes/blog/[slug]/+page.svelte
<script>
  export let data  // receives what load() returned
</script>

<h1>{data.post.title}</h1>
<article>{@html data.post.content}</article>
// src/routes/blog/[slug]/+page.js (isomorphic load)
export async function load({ params, fetch }) {
  // fetch is a SvelteKit-enhanced fetch (handles relative URLs, cookies)
  const res = await fetch(`/api/posts/${params.slug}`)
  const post = await res.json()
  return { post }
}

Q17. What are SvelteKit form actions? Medium

Form actions are server-side handlers for HTML form submissions. They provide progressive enhancement: forms work without JavaScript and are enhanced when JS is available.

// src/routes/login/+page.server.js
import { fail, redirect } from '@sveltejs/kit'

export const actions = {
  default: async ({ request, cookies }) => {
    const data = await request.formData()
    const email = data.get('email')
    const password = data.get('password')

    if (!email || !password) {
      return fail(400, { email, error: 'All fields required' })
    }

    const user = await authenticate(email, password)
    if (!user) {
      return fail(401, { email, error: 'Invalid credentials' })
    }

    cookies.set('session', user.token, { path: '/', httpOnly: true })
    throw redirect(303, '/dashboard')
  },
  // Named action
  logout: async ({ cookies }) => {
    cookies.delete('session', { path: '/' })
    throw redirect(303, '/login')
  }
}

<script>
  import { enhance } from '$app/forms'
  export let form  // receives fail() data
</script>

<form method="POST" use:enhance>
  <input name="email" value={form?.email ?? ''} />
  <input name="password" type="password" />
  {#if form?.error}<p class="error">{form.error}</p>{/if}
  <button>Login</button>
</form>

Q18. What is the difference between SSR, SSG, and CSR in SvelteKit? Medium

SvelteKit supports all three rendering modes configured via page options:

// +page.js or +layout.js

// SSR (default): page rendered on server per request
export const ssr = true  // default
export const csr = true  // default (JS hydration in browser)

// SSG (prerendering): rendered at build time
export const prerender = true

// CSR only: skip SSR, render in browser (for protected pages)
export const ssr = false

// Dynamic prerender based on params
export function entries() {
  return [{ slug: 'post-1' }, { slug: 'post-2' }]
}
ModeWhen to useSEOFirst loadData freshness
SSRDynamic, user-specificGoodFastFresh per request
SSGStatic content, blogsBestFastestBuild-time only
CSRProtected dashboardsPoorSlowerClient-controlled

Q19. What are SvelteKit hooks? Advanced

Hooks intercept requests and responses server-side. src/hooks.server.js handles all server-side requests.

// src/hooks.server.js
export async function handle({ event, resolve }) {
  // Before: auth check, inject locals
  const session = event.cookies.get('session')
  if (session) {
    event.locals.user = await getUserFromSession(session)
  }

  // Resolve the request
  const response = await resolve(event, {
    transformPageChunk: ({ html }) => html.replace('%lang%', 'en')
  })

  // After: add headers
  response.headers.set('X-Custom-Header', 'value')
  return response
}

export async function handleError({ error, event }) {
  // Log to monitoring service
  await logError(error, event.url.pathname)
  return {
    message: 'An unexpected error occurred',
    code: error?.code ?? 'UNKNOWN'
  }
}

// src/hooks.js (isomorphic - runs on both server and client)
export async function handleFetch({ request, fetch, event }) {
  // Intercept all fetch calls (including load functions)
  if (request.url.startsWith('https://api.internal/')) {
    request = new Request(
      request.url.replace('https://api.internal/', 'http://localhost:3000/'),
      request
    )
  }
  return fetch(request)
}

Svelte 5 Runes

Q20. What are runes in Svelte 5? Medium

Runes are compiler-recognized function calls prefixed with $ that make reactivity explicit and work in both .svelte files and plain .js/.ts files.

<script>
  // Svelte 4 (implicit reactivity)
  let count = 0
  $: doubled = count * 2

  // Svelte 5 with runes (explicit)
  let count = $state(0)
  let doubled = $derived(count * 2)
</script>

The four primary runes:

RunePurposeSvelte 4 equivalent
$state()Reactive statelet assignment
$derived()Computed/derived value$: value = ...
$effect()Side effects$: { ... } block
$props()Component propsexport let

Q21. How do you use $state and $derived in Svelte 5? Medium

<script>
  // Primitive state
  let count = $state(0)
  let name = $state('Svelte 5')

  // Object state (deeply reactive)
  let user = $state({
    name: 'Alice',
    profile: { age: 25 }
  })

  // Derived values
  let doubled = $derived(count * 2)
  let greeting = $derived(`Hello, ${name}!`)
  let fullInfo = $derived.by(() => {
    // Complex derivation
    return `${user.name} (age ${user.profile.age})`
  })

  // Mutations work directly (unlike React)
  function birthday() {
    user.profile.age++ // deep mutation tracked
  }
</script>

<p>Count: {count}, Doubled: {doubled}</p>
<p>{greeting}</p>
<button onclick={() => count++}>Increment</button>

Q22. How does $effect work in Svelte 5? Medium

$effect runs after the component mounts and re-runs when its dependencies change. The return value is a cleanup function.

<script>
  let count = $state(0)
  let intervalId

  // Runs after mount, re-runs when count changes (tracked)
  $effect(() => {
    document.title = `Count: ${count}`
  })

  // With cleanup
  $effect(() => {
    const id = setInterval(() => count++, 1000)
    return () => clearInterval(id) // cleanup on re-run/unmount
  })

  // $effect.pre: runs before DOM updates (like beforeUpdate)
  $effect.pre(() => {
    console.log('before DOM update, count =', count)
  })

  // $effect.root: create effects outside component lifecycle
  const cleanup = $effect.root(() => {
    $effect(() => {
      // persists beyond component destruction
    })
    return () => {} // manual cleanup
  })
</script>

Key difference from $: reactive statements: $effect always runs after component initialization and after DOM updates, making it suitable for DOM interactions.

Q23. How do props work in Svelte 5? Medium


<script>
  // All props via $props()
  let { name, count = 0, class: className, ...rest } = $props()

  // TypeScript
  interface Props {
    name: string
    count?: number
    onIncrement?: () => void
  }
  let { name, count = 0, onIncrement }: Props = $props()
</script>

<div class={className}>
  {name}: {count}
  <button onclick={onIncrement}>+</button>
</div>


<Child name="Test" count={5} class="highlight" onIncrement={() => console.log('+')} />

Event handling moves from on:click to onclick (standard DOM event naming) in Svelte 5. Custom events from createEventDispatcher are replaced by callback props.


Performance and Advanced Patterns

Q24. How does Svelte handle transitions and animations? Medium

Svelte has built-in transition and animation directives.

<script>
  import { fade, fly, slide, scale, draw } from 'svelte/transition'
  import { flip } from 'svelte/animate'
  import { tweened, spring } from 'svelte/motion'
  import { cubicOut } from 'svelte/easing'

  let visible = true
  let items = ['a', 'b', 'c']

  // Motion values
  const progress = tweened(0, { duration: 400, easing: cubicOut })
  const coords = spring({ x: 0, y: 0 }, { stiffness: 0.1, damping: 0.25 })
</script>


{#if visible}
  <div transition:fade={{ duration: 300 }}>Fade in/out</div>
  <div in:fly={{ y: 50 }} out:fade>Custom in/out</div>
  <div transition:slide>Slide</div>
{/if}


{#each items as item (item)}
  <div animate:flip={{ duration: 300 }}>{item}</div>
{/each}


<div style="transform: translate({$coords.x}px, {$coords.y}px)" />
<progress value={$progress} />

Q25. What is context in Svelte and when do you use it over stores? Advanced

setContext and getContext pass data down the component tree without prop drilling. Unlike stores, context is per-component-subtree instance, making it suitable for component library patterns where multiple instances need isolated state.

// Parent (e.g., a Tabs component)
import { setContext } from 'svelte'
import { writable } from 'svelte/store'

const activeTab = writable(0)

setContext('tabs', {
  activeTab,
  setActive: (i) => activeTab.set(i)
})

// Child (Tab component, anywhere in subtree)
import { getContext } from 'svelte'

const { activeTab, setActive } = getContext('tabs')

Use context for component library patterns (modal, tabs, form) where multiple independent instances need separate state. Use stores for global app state shared across unrelated parts of the app.

Q26. How does Svelte handle SSR vs Vue/React? Advanced

Svelte compiles to @sveltejs/kit's render function for SSR. SvelteKit handles hydration automatically. The compilation eliminates the VDOM diffing overhead that React and Vue have at runtime.

// Standalone SSR (without SvelteKit)
import { render } from 'svelte/server'
import App from './App.svelte'

const { html, head, css } = render(App, { props: { name: 'SSR World' } })

Key difference: Svelte 5 uses fine-grained reactivity signals (similar to Solid.js) for SSR hydration, sending only the parts of state that need to be reactive to the client.

Q27. What are Svelte actions? Medium

Actions are reusable DOM node behaviors. They run when an element is mounted and can return update/destroy lifecycle functions.

// actions/tooltip.js
export function tooltip(node, params = {}) {
  let { text = '', placement = 'top' } = params
  let tooltipEl

  function show() {
    tooltipEl = document.createElement('div')
    tooltipEl.textContent = text
    tooltipEl.className = `tooltip tooltip-${placement}`
    document.body.appendChild(tooltipEl)
    // position it relative to node
  }

  function hide() {
    tooltipEl?.remove()
  }

  node.addEventListener('mouseenter', show)
  node.addEventListener('mouseleave', hide)

  return {
    update({ text: newText, placement: newPlacement }) {
      text = newText
      placement = newPlacement
    },
    destroy() {
      node.removeEventListener('mouseenter', show)
      node.removeEventListener('mouseleave', hide)
      tooltipEl?.remove()
    }
  }
}

// Usage
import { tooltip } from './actions/tooltip'
<button use:tooltip={{ text: 'Click to save', placement: 'top' }}>
  Save
</button>

Additional Topics

Q28. What are Svelte special elements? Medium


{#if folder.children}
  <svelte:self items={folder.children} />
{/if}


<svelte:component this={currentComponent} {props} />


<svelte:element this={tag} {id} class={cls}>{content}</svelte:element>


<svelte:window on:resize={handleResize} bind:innerWidth={width} />


<svelte:head>
  <title>{pageTitle}</title>
  <meta name="description" content={pageDescription} />
</svelte:head>


<svelte:body on:mouseenter={handleMouseEnter} />


<svelte:options immutable={true} />

Q29. How do you test Svelte components? Advanced

// Using @testing-library/svelte
import { render, fireEvent, screen } from '@testing-library/svelte'
import Counter from './Counter.svelte'

describe('Counter', () => {
  test('increments count on click', async () => {
    render(Counter, { props: { initial: 5 } })

    const button = screen.getByRole('button', { name: /increment/i })
    const count = screen.getByText('Count: 5')

    await fireEvent.click(button)
    expect(screen.getByText('Count: 6')).toBeInTheDocument()
  })

  test('emits event on change', async () => {
    const { component } = render(Counter)
    const mock = vi.fn()
    component.$on('change', mock)

    await fireEvent.click(screen.getByRole('button'))
    expect(mock).toHaveBeenCalledWith(expect.objectContaining({
      detail: 1
    }))
  })
})

For SvelteKit pages, use Playwright for E2E testing with the actual server rendering.

Q30. Predict the output: Advanced

<script>
  import { writable, derived } from 'svelte/store'

  const a = writable(2)
  const b = writable(3)
  const sum = derived([a, b], ([$a, $b]) => $a + $b)

  sum.subscribe(v => console.log('sum:', v))

  $a = 5
</script>

Output:

sum: 5
sum: 8

Explanation: The derived store subscribes immediately and computes the initial value (2 + 3 = 5), logging "sum: 5". When $a = 5 executes (which calls a.set(5)), the derived store recomputes (5 + 3 = 8), logging "sum: 8". This is synchronous for writable stores.


5-Question Mock Test

Q1. Why does items.push(newItem) not update the Svelte UI, and what are two ways to fix it?

Q2. What is the difference between a Svelte store and setContext/getContext? When would you use each?

Q3. In SvelteKit, what is the difference between +page.server.js load and +page.js load? When would you use each?

Q4. What is the output of this Svelte snippet?

<script>
  let x = 0
  $: y = x * 2
  $: z = y + 1
  x = 3
</script>
<p>{y} {z}</p>

Q5. What are Svelte 5 runes and which rune replaces $: reactive declarations?

Answers:

A1. push mutates without assignment; Svelte does not detect it. Fix 1: items = [...items, newItem]. Fix 2: items.push(newItem); items = items (self-assignment triggers invalidation).

A2. Stores are global singletons shared across the entire application. Context is per-subtree and supports multiple independent instances of the same component hierarchy. Use stores for app-wide state (auth, cart); use context for component library isolation (tabs, modals).

A3. +page.server.js runs only on the server: safe for database queries, secrets, cookies. +page.js runs on both server and client (isomorphic): good for public API calls. Use .server.js for authenticated data and secrets; use .js for public data that can also run on the client after navigation.

A4. Output: 6 7. When x = 3, y = 3 * 2 = 6, then z = 6 + 1 = 7. $: statements resolve topologically.

A5. Runes are compiler-recognized function calls that make reactivity explicit. $derived() replaces $: reactive declarations (e.g., $: doubled = x * 2 becomes let doubled = $derived(x * 2)).


Frequently Asked Questions

How is Svelte different from React and Vue?

Svelte is a compiler that generates efficient vanilla DOM manipulation code at build time. React and Vue ship runtime libraries and use virtual DOM diffing. Svelte produces smaller bundles with no framework runtime, but moves complexity to the build step. React and Vue have larger ecosystems and more production tooling.

What is SvelteKit used for?

SvelteKit is the full-stack meta-framework for Svelte, analogous to Next.js for React and Nuxt for Vue. It provides file-based routing, server-side rendering, static site generation, form actions, API endpoints, and adapters for various deployment targets including Node.js, Cloudflare Workers, and static hosting.

What changed from Svelte 4 to Svelte 5?

Svelte 5 introduced runes ($state, $derived, $effect, $props) for explicit reactivity, replacing implicit assignment-based reactivity and $: labels. Event handling moved from on:event directives to standard onevent callback props. The reactivity system was rewritten using fine-grained signals for better performance and predictability.

What is the internal mesh of related topics?

Methodology applied to this articlelast verified 8 Jun 2026
Sources used
Public exam-pattern documents, official recruiter pages, and verified candidate reports on r/developersIndia and LinkedIn.
Verification window
Page last edited 8 Jun 2026 by Aditya Sharma. Numbers and patterns sanity-checked against the most recent 2026 cycle drives we tracked.
What we did NOT do
  • No fabricated salary numbers or success rates. If we quote a range, it's sourced.
  • No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
  • No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
Verification policy: /editorial-standards/. Found something incorrect? Submit a correction - we respond within 48 hours.

topic cluster

More resources in Interview Questions

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

Open Interview Questions hubBrowse all articles

paid contributor programme

Sat this this year? Share your story, earn ₹500.

First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story with byline.

Submit your story →

ready to practice?

Take a free timed mock test

Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.

Start free mock test →
related guides
more from PapersAdda
Company Placement PapersAmazon Placement Papers 2026: SDE-1 OA, Loop and Bar Raiser Guide
19 min read
Company Placement PapersMicrosoft Placement Papers 2026: SDE-1 OA, Loop and AA Round Guide
15 min read
Company Placement PapersAccenture Interview Questions 2026 (with Answers for Freshers)
13 min read
Company Placement PapersAirbnb Placement Papers 2026 – Questions, Answers & Complete Interview Guide
11 min read

Share this guide