How to Use @const in Svelte: Syntax and Examples
In Svelte, use the
@const directive to declare a constant reactive variable that cannot be reassigned. It is written as @const name = value; inside a <script> tag and helps optimize reactivity by signaling immutability.Syntax
The @const directive declares a constant reactive variable in Svelte. It must be used inside the <script> tag. The syntax is:
@const: keyword to declare a constant reactive variable.name: the variable name.= value;: the initial value assigned to the constant.
This variable cannot be reassigned later in the component.
svelte
<script>
@const greeting = 'Hello, world!';
</script>Example
This example shows how to use @const to declare a constant string and display it in the component. The value cannot be changed later.
svelte
<script>
@const greeting = 'Hello, Svelte!';
</script>
<h1>{greeting}</h1>Output
<h1>Hello, Svelte!</h1>
Common Pitfalls
Common mistakes when using @const include:
- Trying to reassign a
@constvariable, which causes an error. - Using
@constoutside the<script>tag. - Confusing
@constwith regularconstdeclarations;@constis reactive and tracked by Svelte.
svelte
<script> @const count = 5; // Wrong: count = 10; // This will cause an error </script>
Quick Reference
| Feature | Description |
|---|---|
| @const declaration | Declares a reactive constant variable |
| Scope | Inside |