2
$: variable = "some string";

This piece of code is syntactically valid in JS as I've learned from Svelte's conference video. I know how it works in Svelte but what purpose does it have in vanilla JS?

I've tried some searching around the web but couldn't find anything that isn't Svelte related.

Do any of you use it on regular basis? Does it have any use cases at all? I'll be glad for any pointers I could get.

  • 2
    That's a *labelled statement*, and `$` is the label. There's no functional reason to do that. – Pointy Aug 28 '19 at 14:46
  • Possible duplicate of [Is using labels in JavaScript bad practice?](https://stackoverflow.com/questions/4906762/is-using-labels-in-javascript-bad-practice) – scrappedcola Aug 28 '19 at 14:49

2 Answers2

5

The syntax is a Labelled Statement.

It lets you declare an identifier that can be used with the break or continue statement on loops generally.

For example:

var str = "";

loop1:
for (var i = 0; i < 5; i++) {
  if (i === 1) {
    continue loop1;
  }
  str = str + i;
}

console.log(str);
// expected output: "0234"

Svelte takes advantage of the availability of the syntax to describe reactivity.

Christian C. Salvadó
  • 807,428
  • 183
  • 922
  • 838
0

xy: is a label which you can use in pair with break and continue. $ has no special role in JavaScript, so just as you (or libraries/frameworks, like jQuery) can use it as identifier for a variable/function, it can also be a label.

See docs here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label

tevemadar
  • 12,389
  • 3
  • 21
  • 49