Skip to main content

Command Palette

Search for a command to run...

JavaScript how to create persistent variable

Updated
1 min read

First method is to return a function inside parent function. Note that the inner function has access to private property of parent.

const incr=(function(v) {
    return function() {
        return ++v;
  }
})(100);

console.log(incr());  //101
console.log(incr());  //102
console.log(incr());  //103

Another way is to define static properties directly.

function f() {}

f.counter=0;
f.incr=function() {
    console.log(f.counter++);
}

f.incr();    //0
f.incr();    //1
f.incr();    //2
f.incr();    //3