Consider this Svelte component code:
<script>
export let name = 'Guest';
</script>
<h1>Hello {name}!
</h1>If you use this component without passing any prop, what will be shown on the page?
<script> export let name = 'Guest'; </script> <h1>Hello {name}!</h1>
Think about the default value assigned to the prop.
The prop name has a default value of 'Guest'. If no value is passed, it uses this default, so the output is 'Hello Guest!'.
count with default 0?Choose the correct Svelte syntax to declare a prop count with a default value of 0.
Remember the order: export then let.
The correct syntax is export let count = 0;. The other options have invalid order or keywords.
Given this Svelte component:
<script>
export let value = 5;
value = value + 3;
</script>
<p>Value is {value}</p>What will be displayed when the component is used with <Component value={10} />?
<script> export let value = 5; value = value + 3; </script> <p>Value is {value}</p>
Remember the prop value is overwritten inside the component.
The prop value is passed as 10, then inside the component it is increased by 3, so the final value is 13.
Look at this code snippet:
<script>
export let count;
count = count + 1;
</script>
<p>Count is {count}</p>When used without passing count, it throws an error. Why?
<script> export let count; count = count + 1; </script> <p>Count is {count}</p>
Think about what happens when you add a number to undefined.
If count is not passed, it is undefined. Adding 1 to undefined results in NaN in JavaScript, but Svelte treats this as an error in this context.
export in Svelte?Consider this Svelte component snippet:
<script>
let title = 'Hello';
</script>
<h1>{title}</h1>If you try to pass a prop named title from a parent component, what will happen?
<script> let title = 'Hello'; </script> <h1>{title}</h1>
Think about how Svelte knows which variables are props.
Only variables declared with export let become props. Without export, the variable is internal and cannot receive values from outside.