Here is the snippet of a Svelte component:
<script>
let radius = 10;
$: area = Math.PI * radius ** 2;
// ...
</script>
Could somebody explain what is the purpose of $:
before the area
variable? Thanks in advance.
It is reactive declaration in Svelte.
It's valid label statement in JavaScript, which Svelte interprets to mean 're-run this code whenever any of the referenced values change'
It is called reactive declaration. Just like your components gets re-rendered whenever an update occurs, the same happens for the reactive declaration.
<script>
let radius = 10;
area = Math.PI * radius ** 2;
// ...
</script>
This sets the area to be Math.PI * 10 **2, but lets say later a function changes radius to 20. Then area will not change and stay as it is. This is where reactive declaration comes in handy. If the radius changes the area is calculated again and is changed.