Curly Braces & Understanding Core Syntax
Curly Braces & Understanding Core Syntax in Svelte
In Svelte, single curly braces {} are used to output or run various elements such as functions, variables, and any single-line expressions. This guide will help you understand how to utilize curly braces effectively in your Svelte applications.
Basic Usage of Curly Braces
Curly braces in Svelte can be used to output:
- Functions 
- Variables 
- Single-line expressions 
Let's explore each of these with examples.
Functions and Variables
You can use curly braces to display the values of functions and variables directly in your HTML. Here’s a simple example:
<script>
    let name = "Shento";
    let age = $state(23);
    function increaseAge() {
        age += 1;
    }
</script>
<h1>Hello, my name is {name}, my age is {age}</h1>
<button onclick={increaseAge}>Increase my age</button>Hello, my name is Shento, my age is 23
Increase my age
Explanation
- name and age: These are variables that can be named anything you like. 
- increaseAge: This is a function that increments the age variable. 
- {name} and {age}: These curly braces are Svelte-specific syntax used to display the values of the variables in the HTML. 
Single-Line Expressions
Curly braces can also be used to evaluate and display single-line expressions. Here’s an example:
<script>
    let name = "Shento";
    let age = 23;
</script>
<h1>Hello, my name is {name.toUpperCase()}, my age in 10 years is {age + 10}</h1>Hello, my name is SHENTO, my age in 10 years is 33
Explanation
- name.toUpperCase(): This is a JavaScript method that converts the name variable to uppercase. 
- age + 10: This is a simple arithmetic expression that adds 10 to the age variable. 
- {name.toUpperCase()} and {age + 10}: These curly braces are used to evaluate and display the expressions in the HTML. 
Additional Information
Warning
Ensure that the expressions inside curly braces are single-line expressions. Multi-line expressions are not supported within curly braces.
Critical Alert
Avoid using complex logic inside curly braces. For better readability and maintainability, keep the logic in the script section and use curly braces only for simple expressions.
Last updated