Consider a parent component that sets a context value and a child component that uses getContext to access it. What will the child component display?
/* Parent.svelte */ <script> import Child from './Child.svelte'; import { setContext } from 'svelte'; setContext('color', 'blue'); </script> <Child /> /* Child.svelte */ <script> import { getContext } from 'svelte'; const color = getContext('color'); </script> <p>The color is {color}</p>
Remember that setContext shares data with child components using the same key.
The parent uses setContext('color', 'blue') to provide the value 'blue'. The child uses getContext('color') to retrieve it, so it displays 'The color is blue'.
Given this Svelte component code, what is the value of theme?
<script> import { getContext } from 'svelte'; const theme = getContext('theme') ?? 'light'; </script>
If no context is set for the key, the fallback value after ?? is used.
No parent component set a context for 'theme', so getContext('theme') returns undefined. The nullish coalescing operator ?? then assigns 'light'.
Choose the code snippet that correctly uses getContext to retrieve a value in a Svelte component.
getContext requires a string key as an argument.
Option A correctly calls getContext with a string key. Option A misses the argument, C uses an undefined variable key, and D uses incorrect syntax.
What happens if a Svelte component calls getContext('missingKey') but no parent component has set this context?
<script> import { getContext } from 'svelte'; const value = getContext('missingKey'); </script>
Check what getContext returns if no context is found.
If no context is set for the key, getContext returns undefined silently without throwing an error.
Which reason best explains why a developer would use getContext instead of passing data via props?
Think about how data flows through nested components.
getContext allows sharing data with deeply nested components without manually passing props through each level, simplifying code and improving maintainability.