DEV Community

Cover image for Keywords in Svelte
Ijay
Ijay

Posted on

Keywords in Svelte

In a programming language, a "keyword" (also known as a "reserved identifier") is a word that has a specific meaning and is used in a specific way according to the syntax of that language. Keywords cannot be used as function names or variable names because they are reserved for special usage in the language. For example, words like "if" and "each" are often keywords in programming languages. If a keyword is used improperly, it can cause an error in the code.

Each programming language has its own set of keywords that are used to define the terms and structures of the language.

These keywords are an essential part of the syntax of the language and must be used correctly for the code to be valid. Understanding and using keywords correctly is an important skill for anyone who wants to write programs in a specific programming language.

Prerequisite

  • Have a suitable Code Editor downloaded. I prefer Visual Studio Code

  • It is advisable to have a good knowledge of JavaScript or libraries like React.js.

  • Install node.js on your system.

keywords In Svelte

Svelte is a unique programming language for front-end development. Unlike other languages, it has a slightly different syntax, and can be easy to make mistakes when first learning it. For example, in Svelte, the onClick event is written as on:click. It is important to understand these differences to avoid mistakes and write effective Svelte code.

What are some of these keywords in svelte

Conditional statement (if)

Conditional statements are used to check if a statement is true or false.

In frameworks like React.js, and Vue.js the if statement is written normally. However, in Svelte, the if statement is wrapped in curly braces{} inside that curly braces({}) is the hash(#) then the condition statement.

For example, let's check the number assigned if it is true or false using an if statement

<script>
   let num = 5
</script>

<main>


{#if num <= 10}
   <p>less than 10</p> //output will true num (5) is less than 10
{/if}

</main>
Enter fullscreen mode Exit fullscreen mode

To check for extra conditions an else if statement is written, but in svelte the keyword is wrapped in curly braces ({}) inside the curly braces a colon(:) before the condition statement.

<script>
    let num = 15
</script>
<main>
{#if num <= 10}
    <p>less than 10</p>
{:else if num <= 15}
    <p>equal to 15</p> //output is true because num (15) is not 
    less than 10 but equal to. The first condition was not true 
    but the 2nd condition was true so it ran
{/if}
</main>
Enter fullscreen mode Exit fullscreen mode

To further check for additional conditions if the previous conditions do not match any condition stated, an else condition will be written

In svelte, the keyword is wrapped in curly braces ({}) inside the curly braces a colon(:) then the condition statement.

<script>
    let num = 25
</script>

<main>
{#if num <= 10}
    <p>less than 10</p>
{:else if num <= 15}
    <p>equal to 15</p> //output is true because num (15) is not less than 10 but equal to. the first condition was not true but the 2nd condition was true so it ran
{:else}
    <p>none is less or equal to</p>//The if or else if will not run because both are true thus it goes down to the default condition
{/if}
</main>
Enter fullscreen mode Exit fullscreen mode

Each()

Each statement can be used to iterate over any collection, such as an object or an array. It allows you to cycle through the data in the collection and output each item as a single element or HTML template in the browser.

In Svelte, each statement is written inside curly braces({}), with the hash(#) before the statement in the array to be iterated.

For example: an each() is used in svelte

<script>
let budgets = [
    {id: 1, name: 'car', amount: 3000,},
    {id: 2, name: 'house', amount: 10000,},
    {id: 3, name: 'staffs', amount: 1000,},
    {id: 4, name: 'family', amount: 2000,},
];
</script>

<h1>Budget</h1>
<main>
    <div>
       {#each budgets as budget (budget.id)}
       <h1>{budget.name}</h1>
       <p> $ {budget.amount}</p>
       {/each}
    </div>
</main>
<style>
h1{
    text-decoration: underline;
}
main{
    text-align: center;
}
</style>
Enter fullscreen mode Exit fullscreen mode

Result

Each()

onClick Event

The onClick event is activated when a button is clicked. It is commonly used in button tags to change the content on a web page.

In Svelte, the onClick event is written as on:click. Many other events in Svelte are written in a similar way, such as on:submit and on:change.

Example of how on:click event is used in button tag (when the button is not triggered)

<script>
// initial data defined
    let name ="Helen"
</script>
<main>
    <button>change name</button>
</main>
Enter fullscreen mode Exit fullscreen mode

Result
onclick

When the on:click event is added this causes the button to be triggered.

<script>
//initial data defined
let name ="Helen"
</script>
//this a function to trigger the on:click event in the button

const changeName=()=>{
    name = "Ifeoma"
}
</script>

<main>
    <h2>{name}</h2>
    <button on:click={changeName}>change name</button>
</main>
Enter fullscreen mode Exit fullscreen mode

Result
change
As earlier said, when the on:click event is added, it triggers the button and brings about a change.

bind:value

The bind:value attribute is used to track the input in an input field. It is a controlled input, which means it updates the content on the web page based on what is entered.

In React.js, this is typically achieved by storing the input in a state form and using an onChange event handler.

In Svelte, the bind:value attribute provides a shorthand and more straightforward way to achieve the same result.

example

<script>
//variable is declared but set to empty string
    let name=" "
</script>

<form>
   <label for="name">name</label>
   <input type="text" bind:value={name}/>
</form>
<h2>{name}</h2>
Enter fullscreen mode Exit fullscreen mode

Result
bind

Reactive statement($:)

A reactive statement automatically updates its value whenever there is a change to the data it is tracking. This allows the statement to always reflect the most current information, without the need for manual data updates.

For example, if a reactive statement is tracking the value of a variable that is changed elsewhere in the code, the reactive statement will immediately reflect the new value.

To declare and assign a value to a reactive variable in Svelte, you can follow these steps:

  • Declare the variable using the let keyword.
  • Assign the value to the variable using the = operator.
  • Declare the reactive statement using the $: prefix.

example

<script>
//the variable is declared first 

let firstName = 'Jane'

let lastName = 'Smith'

// Next reactive statement

$:fullName = firtName + ' ' + lastName

</script>

<div>
    <h3>{fullName}</h3>
</div>

Enter fullscreen mode Exit fullscreen mode

Result
reactive

Event Modifiers

Event modifiers are attributes added to an event. Common event modifiers are self, preventDefault, once, etc.

Let's take preventDefault as an example. The work of preventDefault is to prevent the default action of a form from refreshing.

without the preventDefault Modifier

<script>

//just a function created for the handleSubmit so it will be defined

    const handleSubmit = () =>{}

</script>

<form on:submit={handleSubmit}>

    <h2>Event Modifier</h2>
    <input type="text" />
    <button>submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Result

without
From the video, because a preventDefault was not included, the input refreshed automatically.

Addition of an preventDefault Modifier

<script>
// just a function created for the handleSubmit so it will be defined

    const handleSubmit = () =>{}

</script>

form on:submit|preventDefault={handleSubmit}>

    <h2>Event Modifier</h2>
    <input type="text" />
    <button>submit</button>
</form>
Enter fullscreen mode Exit fullscreen mode

Result

with
The form, can't be refreshed automatically cause the preventDefault Modifier was added.

Slot

In Svelte, the element allows us to pass a child component to another component and render it within the parent component. This makes the child component reusable and allows us to use it multiple times within our application.

For example:

<Parent>
    <Child />
</Parent>
Enter fullscreen mode Exit fullscreen mode

In the example above, the component is passed to the component and rendered inside it using the element. This allows us to easily reuse the component multiple times within our application without needing to duplicate the code.

Why use slot?

  • slot makes the component reusable.

  • slot is good because it allows us as developers to keep the DRY principle.

  • It is clean and easy to debug an error.

  • Component can be easily updated.

A practical example of how the slot works

Slot. svelte component

<button class="button">
    <slot></slot>
</button>

<style>
.button{
    background-color: red;
    border: none;
    outline: none;
    color: white;
    padding:5px;
}
</style>
Enter fullscreen mode Exit fullscreen mode

Next is the Button.svelte component where you want to use it that is what makes it reusable

<script>
//import the file where slot was created

import Button from "./shared/Slot.svelte";

</script>

<h3>slot makes a component reusable</h3>

<Button>
    This is a slot
</Button>
Enter fullscreen mode Exit fullscreen mode

Result
slot

Conclusion

In conclusion, keywords are reserved identifiers in a programming language that have specific meanings and uses. They cannot be used as variable names or function declarations, and using them incorrectly can cause syntax errors.

Resource

Now that you have learned about keywords in Svelte, I encourage you to continue learning and practicing with the language.

Visit the Svelte website to access the official documentation.

Svelte tutorial series by Net Ninja.

These resources will provide you with the information and guidance you need to become more proficient with Svelte.

Thanks for reading if you found this article useful leave a like, comment, and share with your friends

Top comments (0)