Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Svelte: What does $: mean?

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.

like image 810
Marian13 Avatar asked Dec 08 '19 00:12

Marian13


2 Answers

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'

like image 105
Berislav Kovacki Avatar answered Sep 30 '22 13:09

Berislav Kovacki


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.

like image 45
Nour Adel Avatar answered Sep 30 '22 14:09

Nour Adel