Chapter 3: Svelte Basics
.svelte components into targeted DOM updates at build time. Understanding component anatomy, props, expressions, and template control blocks gives you the foundation for every application you will build.
Anatomy of a Svelte Component
Every .svelte file groups its logic, HTML template, and scoped CSS into one cohesive module. Unlike runtime virtual-DOM frameworks, the Svelte compiler analyzes these three blocks together so unused CSS is stripped and reactive variables wire directly to the exact DOM text nodes or attributes that depend on them:
<script>
// Top-level `let` bindings are reactive in Svelte templates
let message = 'Hello, Svelte!';
</script>
<h1>{message}</h1>
<style>
/* Scoped automatically to this component's <h1> via a generated hash class */
h1 {
color: #38bdf8;
font-size: 1.5rem;
}
</style>
Sections Explained:
Each section plays a distinct role and can be omitted when a component does not need it:
<script>: Holds component state, imports, helper functions, and prop declarations. Code here runs once when the component instance is created.- Markup: Standard HTML extended with curly-brace JavaScript expressions, template blocks (
{#if},{#each}), and directives (on:,bind:). <style>: CSS rules automatically scoped to elements in this component, preventing accidental style leaks across the rest of the application.
Working with Props
Props pass data from a parent component down to a child component. In Svelte, prefixing a variable with export let in the child's <script> block declares it as an external prop. Providing a default value makes the prop optional and prevents undefined from rendering in the DOM when the parent omits it:
<script>
// `name` defaults to 'World' if the caller omits it; `role` is optional
export let name = 'World';
export let role = 'Learner';
</script>
<p>Hello, {name} ({role})!</p>
A parent component passes props just like HTML attributes, or uses curly braces to pass dynamic JavaScript values and objects:
<Greeting name="Alice" role="Engineer" />
Treat props as read-only inputs unless you explicitly opt into two-way binding with bind:. Mutating a prop inside a child without parent coordination creates hard-to-trace state drift.
Displaying Data
Curly braces {...} evaluate any JavaScript expression—variables, arithmetic, method calls, or formatted strings—and escape the result safely against HTML injection. To render lists, wrap repeated markup in an {#each} block and supply a unique key expression in parentheses (item.id) so Svelte can reorder, insert, or remove rows without recreating unchanged DOM nodes:
<script>
let count = 0;
let items = [
{ id: 1, label: 'Apple' },
{ id: 2, label: 'Banana' },
{ id: 3, label: 'Orange' }
];
</script>
<p>Total items: {items.length} (selected: {count})</p>
<ul>
{#each items as item, index (item.id)}
<li>{index + 1}. {item.label}</li>
{:else}
<li>No items in the list.</li>
{/each}
</ul>
Notice the optional {:else} clause inside {#each}: it renders automatically when the array is empty, eliminating a separate length check.
Conditional Rendering
HTML has no built-in branching syntax, so Svelte provides {#if}, {:else if}, and {:else} blocks. Only the active branch is mounted in the DOM, which keeps event listeners and child component state clean when switching between loading, error, and ready views:
<script>
export let status = 'loading'; // 'loading' | 'ready' | 'error'
</script>
{#if status === 'loading'}
<p>Loading workspace...</p>
{:else if status === 'error'}
<p role="alert">Could not load workspace.</p>
{:else}
<p>Workspace is ready.</p>
{/if}
Practice: Build a ProductCard.svelte component that accepts title, price, and inStock props, renders a formatted price badge, and uses {#if} to switch between an active status and an out-of-stock notice.