In this article, we will look at how to output JavaScript variables in Svelte. We will begin by creating a basic project structure using the Svelte + Vite template.
Let’s run the below command to create the project folder.
npm create vite@latest variables-svelte-project -- --template svelte
This will create a folder variables-svelte-project
in your current working directory. Feel free to change it to any name you would like for your svelte project.
Next, navigate to the project folder and install all the packages required for the Svelte project by running the following command.
npm install
Once, the packages are installed, start the development server.
npm run dev
This will run our server on port 5173 by default. Open your web browser and visit http://localhost:5173/
The root component of the application is found in App.svelte
file under the src
directory. This file contains the default code. For demonstration, I will clear the content of App.svelte
and write the code from scratch.
curly braces {}
Svelte uses curly braces {}
to interpolate javascript variables. Let’s see how it works.
Open the App.svelte
file and include the below code.
<script>
let message = "Hello World";
</script>
<h1>{message}</h1>
The above contains a variable message
which is displayed using the h1
element. The message
variable is wrapped with the curly braces {}
for interpolation.
If the value of the variable changes, in its response, Svelte automatically updates the user interface to reflect the changes. Let’s illustrate this with an example:
<script>
let message = "Hello World";
setTimeout(function () {
message = "Good Morning";
}, 2000);
</script>
<h1>{message}</h1>
In the above example, we use the setTimeOut
function to update the value of message
variable to “Good Morning” after a delay of 2 seconds.
Due to the reactivity in Svelte, the change in the message
variable triggers an automatic update of the template. The <h1>
tag will now display the text “Good Morning” as seen in the below screenshot.