Skip to main content
Svelte Fundamentals
CHAPTER 04 Beginner

Svelte Syntax and Components

Updated: May 18, 2026
5 min read

# CHAPTER 4

Svelte Syntax and Components

1. Chapter Introduction

A Svelte component is a .svelte file that contains HTML, JavaScript, and CSS all in one place — no .jsx, no .ts alongside .css, no .html + .js pairs. This colocation makes components self-contained and highly readable. In this chapter, we master Svelte's component syntax and build our first reusable User Profile component.

2. Learning Objectives

  • Write a complete Svelte component with script, markup, and style sections.
  • Declare and use variables in templates using { }.
  • Use reactive declarations ($:).
  • Import and use child components.
  • Export props using export let.

3. The Single File Component (SFC) Structure

svelte
1234567891011121314151617181920212223
<!-- MyComponent.svelte -->

<!-- SECTION 1: JavaScript Logic -->
<script>
  let name = &#039;Alice';
  let count = 0;
</script>

<!-- SECTION 2: HTML Markup (Template) -->
<div class="card">
  <h2>{name}</h2>
  <p>Count: {count}</p>
</div>

<!-- SECTION 3: Scoped CSS -->
<style>
  .card {
    padding: 1rem;
    border: 1px solid #ddd;
    border-radius: 8px;
  }
  h2 { color: #333; }
</style>

4. Template Expressions { }

Inside the markup, { } interpolates any JavaScript expression:
svelte
123456789
<script>
  let price = 29.99;
  let quantity = 3;
  let user = { name: &#039;Bob', role: 'Admin' };
</script>

<p>Price: ${price}</p>
<p>Total: ${price * quantity}</p>
<p>{user.name} — {user.role.toUpperCase()}</p>

5. Reactive Declarations $:

The $: label marks a statement as reactive. It re-runs whenever any variable it depends on changes:
svelte
12345678910111213141516171819
<script>
  let width = 10;
  let height = 5;

  // This automatically recalculates when width or height changes!
  $: area = width * height;
  $: perimeter = 2 * (width + height);

  // Reactive block — runs any code when dependencies change
  $: {
    console.log(`Dimensions changed: ${width} x ${height}`);
    document.title = `Area: ${area}`;
  }
</script>

<input type="number" bind:value={width} />
<input type="number" bind:value={height} />
<p>Area: {area}</p>
<p>Perimeter: {perimeter}</p>

6. Creating Reusable Components

svelte
123456789101112131415161718192021222324252627282930313233343536373839404142434445
<!-- src/lib/UserCard.svelte -->
<script>
  export let name;          // Props use 'export let'
  export let role = &#039;User'; // Default value
  export let avatar = &#039;';
</script>

<div class="user-card">
  {#if avatar}
    <img src={avatar} alt="{name}&#039;s avatar" />
  {:else}
    <div class="avatar-placeholder">{name[0]}</div>
  {/if}
  <h3>{name}</h3>
  <span class="badge">{role}</span>
</div>

<style>
  .user-card {
    display: flex;
    align-items: center;
    gap: 1rem;
    padding: 1rem;
    border: 1px solid #e5e7eb;
    border-radius: 12px;
  }
  .badge {
    background: #ede9fe;
    color: #7c3aed;
    padding: 0.25rem 0.75rem;
    border-radius: 999px;
    font-size: 0.875rem;
  }
  .avatar-placeholder {
    width: 48px;
    height: 48px;
    border-radius: 50%;
    background: #7c3aed;
    color: white;
    display: grid;
    place-items: center;
    font-size: 1.25rem;
    font-weight: bold;
  }
</style>
svelte
12345678
<!-- App.svelte — Using the component -->
<script>
  import UserCard from &#039;./lib/UserCard.svelte';
</script>

<UserCard name="Alice Johnson" role="Senior Developer" />
<UserCard name="Bob Smith" role="Designer" />
<UserCard name="Carol Davis" /> <!-- Uses default role=&#039;User' -->

7. Dynamic Attributes

svelte
1234567891011121314
<script>
  let isActive = true;
  let buttonText = &#039;Click Me';
  let imageUrl = &#039;https://example.com/image.jpg';
</script>

<!-- Dynamic class -->
<div class:active={isActive}>Content</div>

<!-- Dynamic attribute -->
<img src={imageUrl} alt="Dynamic image" />

<!-- Shorthand: if variable name matches attribute name -->
<img {src} alt="..." />  <!-- equivalent to src={src} -->

8. Mini Project: User Profile Component

svelte
123456789101112131415161718192021222324252627282930
<!-- ProfileCard.svelte -->
<script>
  export let name;
  export let title;
  export let followers = 0;
  export let following = 0;
  export let bio = &#039;';

  $: initials = name.split(&#039; ').map(w => w[0]).join('').toUpperCase();
</script>

<div class="profile-card">
  <div class="avatar">{initials}</div>
  <h2>{name}</h2>
  <p class="title">{title}</p>
  <p class="bio">{bio}</p>
  <div class="stats">
    <div><strong>{followers.toLocaleString()}</strong><span>Followers</span></div>
    <div><strong>{following.toLocaleString()}</strong><span>Following</span></div>
  </div>
</div>

<style>
  .profile-card { text-align: center; padding: 2rem; border-radius: 16px; background: white; box-shadow: 0 4px 20px rgba(0,0,0,0.1); }
  .avatar { width: 80px; height: 80px; border-radius: 50%; background: linear-gradient(135deg, #667eea, #764ba2); color: white; font-size: 2rem; font-weight: bold; display: grid; place-items: center; margin: 0 auto 1rem; }
  .stats { display: flex; justify-content: center; gap: 2rem; margin-top: 1rem; }
  .stats div { display: flex; flex-direction: column; }
  .stats strong { font-size: 1.25rem; }
  .stats span { color: #666; font-size: 0.875rem; }
</style>

9. Common Mistakes

  • Forgetting export let for props: If you use let name instead of export let name, the variable is local and cannot be passed from the parent.
  • Using {} for HTML attributes without the correct syntax: class="{myClass}" is fine but class={myClass} is more idiomatic in Svelte.

10. MCQs with Answers

Question 1

How do you declare a prop (a variable received from a parent) in Svelte?

Question 2

What syntax interpolates a JavaScript variable into Svelte HTML?

Question 3

What does $: area = width * height do?

Question 4

How do you import a child component?

Question 5

How do you give a prop a default value in Svelte?

Question 6

Are CSS styles in a .svelte file scoped or global?

Question 7

What shorthand can you use when a variable name matches an attribute name?

Question 8

What directive conditionally adds a CSS class?

Question 9

What label is used for reactive statements in Svelte?

Question 10

Can a Svelte component have multiple <style> blocks?

11. Interview Questions

  • Q: What is a Single File Component in Svelte? What are its advantages?
  • Q: Explain reactive declarations ($:). How do they differ from computed properties in Vue?

12. Summary

Svelte's single-file component format is elegant and productive. By combining script, markup, and styles in one file with automatic CSS scoping and simple reactive declarations ($:), Svelte eliminates the configuration overhead and boilerplate that plagues larger frameworks. A self-contained, reusable component can be written in just 20 lines.

13. Next Chapter Recommendation

Variables update the DOM. But what exactly happens when a variable changes? In Chapter 5: Reactivity in Svelte, we deep-dive into Svelte's revolutionary compiler-based reactivity system and build a live counter application.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·