What is this : sign after a variable JS syntax?
This is label in JavaScript.
The interesting point here is how Svelte is using this to bind variables to other variables. Here's a portion of a video where Rich Harris explains this.
Essentially, in Svelte, $:
means re-run whenever these values change
If we look a the example in Svelte's Reactive declarations example,
<script>
let count = 1;
// the `$:` means 're-run whenever these values change'
$: doubled = count * 2;
$: quadrupled = doubled * 2;
function handleClick() {
count += 1;
}
</script>
<button on:click={handleClick}>
Count: {count}
</button>
<p>{count} * 2 = {doubled}</p>
<p>{doubled} * 2 = {quadrupled}</p>
The variables doubled
and quadrupled
have $
label. So, they'll be computed again when count
or doubled
changes respectively.
If you take a look at the compiled code, you can see
let doubled, quadrupled;
$$self.$$.update = ($$dirty = { count: 1, doubled: 1 }) => {
if ($$dirty.count) { $$invalidate('doubled', doubled = count * 2); }
if ($$dirty.doubled) { $$invalidate('quadrupled', quadrupled = doubled * 2); }
};
So, each time the update happens, there is a dirty check for those variables and update.
In conclusion. $:
in Svelte doesn't have anything to do with JavaScript label. It's a directive for Svelte compiler to have the code for updating those variables. $:
is of course valid syntax but outside the context of Svelte, it doesn't do what it does in Svelte. It's the compilation that does the magic ;)
Any JavaScript statement (kind-of except function declarations) can be preceded by a label:
foo: var x = 0;
What you've got there is something like that:
$: doubled = 6 * 2;
In your statement, "$" is the label.
There's not much point to labelled statements because there's no goto
in JavaScript. Both break
and continue
can include a label of an enclosing loop to indicate how many "layers" should be involved.
wholeLoop:
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] == null)
// Oh no! This is terrible
break wholeLoop;
}
}
MDN, spec
All the above is pretty much correct, but apparently Svelte applies its own build-time preprocessor to component source code and translates that into the actual JavaScript sent to the browser. This use of the label syntax is "hijacked" by them to mean something; see Quentin's answer.