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
4. Template Expressions { }
Inside the markup, { } interpolates any JavaScript expression:
svelte
5. Reactive Declarations $:
The $: label marks a statement as reactive. It re-runs whenever any variable it depends on changes:
svelte
6. Creating Reusable Components
svelte
svelte
7. Dynamic Attributes
svelte
8. Mini Project: User Profile Component
svelte
9. Common Mistakes
-
Forgetting
export letfor props: If you uselet nameinstead ofexport 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 butclass={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.