[proposal] Persistent variables in functions/methods

Herbert Vojčík herby at mailbox.sk
Wed Jul 25 11:02:16 UTC 2018



Neek Sandhu wrote on 17. 7. 2018 6:56:
> 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;
>  � � }
> })()
> ```

If we get do expressions, we can, afaict, simply do

   const foo = do {
     let counter = 0;
     const httpRE = /^https?/;
     n => {
       counter++;
       return n * a;
     }
   };


More information about the es-discuss mailing list