[proposal] Persistent variables in functions/methods

Neek Sandhu neek.sandhu at outlook.com
Tue Jul 17 04:56:47 UTC 2018

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

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?/;

    return n * a;

is 1:1 as

let foo = (() => {
    let counter = 0;
    const httpRE = /^https?/;
    return (n) => {
        return  n * a;

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20180717/850d45b3/attachment.html>

More information about the es-discuss mailing list