[proposal] Persistent variables in functions/methods

Naveen Chawla naveen.chwl at gmail.com
Tue Jul 17 06:23:56 UTC 2018


Seems attractive at first, but the problem for me is readability. It seems
to me that we are trained to understand variable assignments as happening
where they are written, e.g.

```js
persist let counter = 0;

counter++;
```

With the "persist" feature, the value of counter after `counter++` could be
67, or 189. However, it seems to me that we are trained to understand that
the value of counter after `counter++` would be 1. Because upon glance we
may have expected the let declaration to be executed each time where it is
written in the function.

On Tue, 17 Jul 2018 at 10:26 Neek Sandhu <neek.sandhu at outlook.com> wrote:

> It'd be really useful to have variables inside methods/functions that are
> initialized once, reused for subsequent calls and live as long as
> containing scope i.e the function itself.
>
> > not to be confused with `static` properties
>
> ## Use Cases
>
> Almost every app has a function or method that needs to "preserve" some
> state across multiple calls, a counter for example. Current ways out of
> this situation are either closures created with IIFE's or making those
> variables top-level. Both of which are ugly. I think the same could be done
> much more neatly with persistent variables.
>
> ## Example
>
> ```javascript
> function foo(n) {
>     // initialized on first call to foo, persists for subsequent calls
>     persist let counter =  0;
>
>     // this way JS engine won't have to recompile the pattern everytime
>     persist const httpRE = /^https?/;
>
>     counter++;
>     return n * a;
> }
> ```
>
> is 1:1 as
>
> ```javascript
> let foo = (() => {
>     let counter = 0;
>     const httpRE = /^https?/;
>     return (n) => {
>         counter++;
>         return  n * a;
>     }
> })()
> ```
>
> _______________________________________________
> es-discuss mailing list
> es-discuss at mozilla.org
> https://mail.mozilla.org/listinfo/es-discuss
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180717/eee8e083/attachment.html>


More information about the es-discuss mailing list