0

The Svelte tutorial presents line

$: doubled = count * 2;

And claims

[..] It's valid (if unconventional) JavaScript [..]

If it's valid in plain JavaScript, what's the meaning of it?

I tried it in the console and $: tt = 5 seems to assign a value of 5 to tt but does nothing to $. It also seems that I can place other strings at the start like fdf: ddd = 44 and it works the same.

Note: I am NOT asking about the role of this in Svelte but in plain JS without Svelte compiler.

1
  • The string of characters before the : is a label
    – 4castle
    Aug 10, 2019 at 23:31

1 Answer 1

1

This is the syntax for a label. It is typically used if you have nested loops and you want to break out of the further out loop:

loop1:
for (i = 0; i < 3; i++) {      //The first for statement is labeled "loop1"
   loop2:
   for (j = 0; j < 3; j++) {   //The second for statement is labeled "loop2"
      if (i === 1 && j === 1) {
         break loop1; // this exits out of both loops
      }
      break loop2; // this leaves only the inner "j" loop
      break;       // This does the same thing as "break loop2"
   }
}

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label for more reference information.

2
  • Is there any meaning to label a declaration? It seems that placing loop1: x = 5 at the start (or anywhere else) makes the label unusable (undefined) at every other line. Am I missing something?
    – Džuris
    Aug 10, 2019 at 23:43
  • 1
    Correct, having a label there doesn't change the assignment in anyway (in non-svelte javascript). It is exactly because this label syntax is allowed in too many places that it was "up for grabs" for svelte to safely reuse it.
    – George
    Aug 11, 2019 at 1:34

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