0
0
Svelteframework~10 mins

Default prop values in Svelte - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Default prop values
Component receives props
Check if prop is passed
Use passed prop
Render component with prop value
When a Svelte component receives props, it checks if a prop was passed. If not, it uses the default value before rendering.
Execution Sample
Svelte
  <script>
    export let name = 'Guest';
  </script>

  <p>Hello, {name}!</p>
This Svelte component greets the user by name or uses 'Guest' if no name is passed.
Execution Table
StepProp 'name' passed?Value of 'name'Rendered Output
1Yes ('Alice')'Alice'<p>Hello, Alice!</p>
2No'Guest'<p>Hello, Guest!</p>
3No'Guest'<p>Hello, Guest!</p>
💡 Rendering completes after using passed or default prop value.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3
name'Guest' (default)'Alice''Guest''Guest'
Key Moments - 2 Insights
Why does the component show 'Guest' when no name is passed?
Because the default value 'Guest' is assigned to 'name' in the export statement, as shown in execution_table rows 2 and 3.
What happens if a prop is passed to the component?
The passed prop value overrides the default, as seen in execution_table row 1 where 'name' is 'Alice'.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of 'name' at Step 2?
A'Alice'
B'Guest'
Cundefined
Dnull
💡 Hint
Check the 'Value of name' column in execution_table row 2.
At which step does the component render 'Hello, Alice!'?
AStep 1
BStep 2
CStep 3
DNone
💡 Hint
Look at the 'Rendered Output' column in execution_table.
If we change the default value to 'Friend', what will be the rendered output at Step 3?
A<p>Hello, Alice!</p>
B<p>Hello, Guest!</p>
C<p>Hello, Friend!</p>
D<p>Hello, undefined!</p>
💡 Hint
Refer to variable_tracker and how default values affect rendering when no prop is passed.
Concept Snapshot
Svelte default prop values:
- Use export let prop = defaultValue;
- If parent passes prop, use it.
- Else, use defaultValue.
- Ensures component always has a value.
- Simplifies component usage.
Full Transcript
In Svelte, components can have default prop values by assigning them during export, like export let name = 'Guest'. When the component is used, if a parent passes a value for 'name', that value is used. If not, the default 'Guest' is used instead. This ensures the component always has a value to display. The execution table shows three steps: when 'Alice' is passed, the component renders 'Hello, Alice!'. When no prop is passed, it renders 'Hello, Guest!'. The variable tracker confirms the 'name' variable changes accordingly. This pattern helps avoid undefined props and makes components easier to use.