Understanding the $ in Svelte

·

2 min read

Before we start:

I decided to write this article because, while using Svelte, I found the $ symbol to be a bit mysterious at first. But the truth is, it's the key to implementing responsive logic. Through this article, I'll explain how the $ symbol works and how you can use it to create responsive logic in Svelte.

Content:

<script>
    export let title;
    let count = 0;
    $: {
        console.log(`multiple statements can be combined`);
        console.log(`the current title is ${title}`);
    }

</script>
<p>{title}</p>
<button on:click={() => { title = count++}}>TEST</button>

In this example, we'll explore how the $ symbol creates responsive variables. Whenever 'title' changes, the $ block gets executed, which contains multiple statements. Even though 'count' isn't directly used inside the $ block, 'title' is, creating a dependency. So, when 'title' changes, the entire $ block runs, including the console.log statements.

<script>
    export let num = 0;
    $: squared = num * num;
    $: cubed = squared * num;

    $: {
        console.log(`squared is ${squared}`)
        console.log(`cubed is ${cubed}`)
    }
</script>
<p>{squared}</p>
<p>{cubed}</p>
<button on:click ={()=>{num += 1}}>test</button>

This code demonstrates:

  • Defining variables using $.

  • Increasing the 'num' variable's value by clicking the button, causing changes in 'squared' and 'cubed' and triggering responsive updates.

  • When the dependencies for assignment change (in this example, it's 'num'), the variable's value gets updated before the component updates.

  • Any change in variables within ${} triggers the functions defined within $.

Conclusion

We embarked on a journey to demystify the enigmatic $ symbol in Svelte. It's far more than just a character; it's the linchpin for creating responsive logic within your Svelte components.

Hope you like it.