Performance: Optional parameters
Optional parameters affect how components receive and handle data, impacting initial rendering and reactivity updates.
<script> export let title = "Default Title"; export let subtitle = null; </script> <h1>{title}</h1> {#if subtitle} <h2>{subtitle}</h2> {/if}
<script> export let title; export let subtitle; </script> <h1>{title}</h1> {#if subtitle} <h2>{subtitle}</h2> {/if}
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| No default for optional params | Extra reactive checks | Multiple reflows if params change | Higher paint cost due to re-renders | [X] Bad |
| Default values for optional params | Minimal reactive triggers | Single reflow on change | Lower paint cost with stable updates | [OK] Good |
export let to receive values from outside.= defaultValue means the prop is optional and uses that value if none is passed.export let propName = defaultValue; -> Option A= value in the parameter list.name = 'Guest', which is valid and makes the parameter optional. <script>
export let greeting = 'Hello';
export let name;
</script>
<p>{greeting}, {name || 'Friend'}!</p><Component /> with no props passed?greeting has default 'Hello', name is undefined because no prop passed.{name || 'Friend'} uses 'Friend' because name is falsy (undefined).<script>
export let count;
if (count === undefined) {
count = 10;
}
</script>export let count = 10;, not by reassigning later.size prop with default 'medium' and an optional color prop with default 'blue'. Which code correctly implements this and uses both props in the template?export let and assigned default values directly.{size} and {color} inside style attribute is correct.<script>
export let size = 'medium';
export let color = 'blue';
</script>
<div style="font-size: {size}; color: {color};">Styled Text</div> -> Option BPass the test and this pattern moves unknown