Skip to main content

We're not limited to declaring reactive values — we can also run arbitrary statements reactively. For example, we can log the value of count whenever it changes:

ts
$: console.log('the count is ' + count);

You can easily group statements together with a block:

ts
$: {
console.log('the count is ' + count);
alert('I SAID THE COUNT IS ' + count);
}

You can even put the $: in front of things like if blocks:

ts
$: if (count >= 10) {
alert('count is dangerously high!');
count = 9;
}
App.svelte
<script>
let count = 0;

function handleClick() {
count += 1;
}
</script>

<button on:click={handleClick}>
Clicked {count}
{count === 1 ? 'time' : 'times'}
</button>

/* App.svelte generated by Svelte v4.2.19 */
import {
SvelteComponent,
append,
detach,
element,
init,
insert,
listen,
noop,
safe_not_equal,
set_data,
space,
text
} from "svelte/internal";

import "svelte/internal/disclose-version";

function create_fragment(ctx) {
let button;
let t0;
let t1;
let t2;
let t3_value = (/*count*/ ctx[0] === 1 ? 'time' : 'times') + "";
let t3;
let mounted;
let dispose;

return {
c() {
button = element("button");
t0 = text("Clicked ");
t1 = text(/*count*/ ctx[0]);
t2 = space();
t3 = text(t3_value);
},
m(target, anchor) {
insert(target, button, anchor);
append(button, t0);
append(button, t1);
append(button, t2);
append(button, t3);

if (!mounted) {
dispose = listen(button, "click", /*handleClick*/ ctx[1]);
mounted = true;
}
},
p(ctx, [dirty]) {
if (dirty & /*count*/ 1) set_data(t1, /*count*/ ctx[0]);
if (dirty & /*count*/ 1 && t3_value !== (t3_value = (/*count*/ ctx[0] === 1 ? 'time' : 'times') + "")) set_data(t3, t3_value);
},
i: noop,
o: noop,
d(detaching) {
if (detaching) {
detach(button);
}

mounted = false;
dispose();
}
};
}

function instance($$self, $$props, $$invalidate) {
let count = 0;

function handleClick() {
$$invalidate(0, count += 1);
}

return [count, handleClick];
}

class App extends SvelteComponent {
constructor(options) {
super();
init(this, options, instance, create_fragment, safe_not_equal, {});
}
}

export default App;
result = svelte.compile(source, {
generate:
css:
});
/* Add a <style> tag to see compiled CSS */