Performance: Why special elements handle edge cases
This concept affects how efficiently the browser updates the UI when special elements handle unusual or complex cases.
<script> let items = []; // Using keyed each block to update only changed items function updateItems(newItems) { items = newItems; } </script> <ul> {#each items as item (item.id)} <li>{item.name}</li> {/each} </ul>
<script> let items = []; // Updating entire list on any change function updateItems(newItems) { items = newItems; } </script> <ul> {#each items as item} <li>{item}</li> {/each} </ul>
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Non-keyed each block | Updates all list items | Multiple reflows per update | High paint cost | [X] Bad |
| Keyed each block | Updates only changed items | Single or few reflows | Low paint cost | [OK] Good |
{#if} and {#each} exist?{#if} and {#each} manage UI changes based on conditions or lists.{#if condition} ... {/if} to conditionally render content.{#if condition} ... {/if} matches the exact Svelte syntax for conditions.{#if condition} ... {/if} [OK]{`\n{#each items as item}\n {item}
\n{/each}`}for each item.
apple
andbanana
.{`{#if user.isLoggedIn}\n Welcome, {user.name}!
\n{/if}`}user.name is valid JavaScript and works in Svelte templates.{#each users as user}
{#if user.active}
<p>{user.name}</p>
{/if}
{/each} uses an {#if} inside {#each} to check user.active, correctly handling edge cases without filtering the array upfront.{#each users.filter(u => u.active) as user}
<p>{user.name}</p>
{/each} missing as user in original {#each users.filter(u => u.active)}
<p>{user.name}</p>
{/each}, so user undefined and no names render; {#if users.active}
<p>{users.name}</p>
{/if} wrongly checks users.active (not per user); {#each users as user}
<p>{user.active ? user.name : ''}</p>
{/each} renders empty paragraphs for inactive users.Pass the test and this pattern moves unknown