Skip to content

Commit 7c6333e

Browse files
committed
docs: how to javascript
1 parent 94694a5 commit 7c6333e

File tree

1 file changed

+87
-0
lines changed

1 file changed

+87
-0
lines changed

documentation/docs/02-runes/02-$state.md

Lines changed: 87 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -127,3 +127,90 @@ To take a static snapshot of a deeply reactive `$state` proxy, use `$state.snaps
127127
```
128128

129129
This is handy when you want to pass some state to an external library or API that doesn't expect a proxy, such as `structuredClone`.
130+
131+
## Passing state into functions
132+
133+
JavaScript is a _pass-by-value_ language — when you call a function, the arguments are the _values_ rather than the _variables_. In other words:
134+
135+
```js
136+
/// file: index.js
137+
// @filename: index.js
138+
// ---cut---
139+
/**
140+
* @param {number} a
141+
* @param {number} b
142+
*/
143+
function add(a, b) {
144+
return a + b;
145+
}
146+
147+
let a = 1;
148+
let b = 2;
149+
let total = add(a, b);
150+
console.log(total); // 3
151+
152+
a = 3;
153+
b = 4;
154+
console.log(total); // still 3!
155+
```
156+
157+
If `add` wanted to have access to the _current_ values of `a` and `b`, and to return the current `total` value, you would need to use functions instead:
158+
159+
```js
160+
/// file: index.js
161+
// @filename: index.js
162+
// ---cut---
163+
/**
164+
* @param {() => number} getA
165+
* @param {() => number} getB
166+
*/
167+
function add(+++getA, getB+++) {
168+
return +++() => getA() + getB()+++;
169+
}
170+
171+
let a = 1;
172+
let b = 2;
173+
let total = add+++(() => a, () => b)+++;
174+
console.log(+++total()+++); // 3
175+
176+
a = 3;
177+
a = 4;
178+
console.log(+++total()+++); // 7
179+
```
180+
181+
State in Svelte is no different — when you reference something declared with the `$state` rune...
182+
183+
```js
184+
let a = +++$state(1)+++;
185+
let b = +++$state(2)+++;
186+
```
187+
188+
...you're accessing its _current value_.
189+
190+
Note that 'functions' is broad — it encompasses properties of proxies and [`get`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/get)/[`set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/set) properties...
191+
192+
```js
193+
/// file: index.js
194+
// @filename: index.js
195+
// ---cut---
196+
/**
197+
* @param {{ a: number, b: number }} input
198+
*/
199+
function add(input) {
200+
return {
201+
get value() {
202+
return input.a + input.b;
203+
}
204+
};
205+
}
206+
207+
let input = $state({ a: 1, b: 2 });
208+
let total = add(input);
209+
console.log(total.value); // 3
210+
211+
input.a = 3;
212+
input.b = 4;
213+
console.log(total.value); // 7
214+
```
215+
216+
...though if you find yourself writing code like that, consider using [classes](#Classes) instead.

0 commit comments

Comments
 (0)