10

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.

0

2 Answers 2

23

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'

3

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.