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.
The solution to your problem is to make the
console.log(greeting)statement reactive as well:Because
console.logis 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 executedgreetinghas not yet been set (your first error) or it has been set toundefinedthrough thelet greetingdeclaration (your second error).By making
console.logreactive, you ensure it will be executed (a) aftergreetinghas been set (which solves your first issue), and (b) every timegreetingis set (which solves your second issue). And you do not have to declaregreetingprior to assigning it a value in a reactive statement.