Why can't I access a "$:" aka reactive variable inside the script tags in svelte3?

1k views Asked by At

I am pretty new to svelte started it a week ago......

I am trying to know about it i really loved❤️❤️ it but I have a problem☹️☹️

I am trying to access a $: variable in the script tags but i get an Error Cannot access 'greeting' before initialization.

<script>
    let name = 'world';
    $: greeting = `Hello ${name}`
    console.log(greeting)
</script>

<h1>Hello {name}!</h1>

I also tried declaring the variable with let prior to using it

    let greeting

But in this case console.log outputs undefined.

1

There are 1 answers

1
Thomas Hennes On BEST ANSWER

The solution to your problem is to make the console.log(greeting) statement reactive as well:

<script>
    let name = 'world';
    $: greeting = `Hello ${name}`
    $: console.log(greeting)
</script>

<h1>Hello {name}!</h1>

Because console.log is not a reactive statement in your example, it is actually executed before any reactive statement, following the 'normal' flow execution of your script. So when it is executed greeting has not yet been set (your first error) or it has been set to undefined through the let greeting declaration (your second error).

By making console.log reactive, you ensure it will be executed (a) after greeting has been set (which solves your first issue), and (b) every time greeting is set (which solves your second issue). And you do not have to declare greeting prior to assigning it a value in a reactive statement.