0

I have a revealing module pattern.

Let me understand where the variable val is stored after calling createCounter() in counter1 and counter2.

createCounter creates object including increment() and getVal() methods in counter1 and counter2. If we console.log these two variables we get objects. But where is the val stored?

Does two different val exist in corresponding scope of the variables counter1 and counter2? The concept just does not click in my mind.

Can we anyhow console val which corresponds to counter1 and counter2?

function createCounter() {
    let val = 0;
    return {
        increment() { val++ },
        getVal() { return val }
    }
}

let counter1 = createCounter();
counter1.increment();
console.log(counter1.getVal()); // 1
counter1.increment();
console.log(counter1.getVal()); // 2


let counter2 =  createCounter();
console.log(counter2.getVal()) // 0
madfcat
  • 74
  • 1
  • 9
  • 1
    Each time you call `createCounter()`, a new `val` is stored into memory with scope of `createCounter`. The returned functions hold references to that specific `val` variable, meaning multiple creations of `createCounter` do not reference the same `val`. However, you have to be careful here as you could possibly memory leak if you don't properly dispose of the value. – code Jan 14 '23 at 22:21
  • What would be the right way to dispose it though? – madfcat Jan 14 '23 at 22:25
  • 1
    "*I have a revealing module pattern.*" - [no](https://stackoverflow.com/q/22906662/1048572). You have a (factory) function returning an object with closures. – Bergi Jan 14 '23 at 22:29
  • 1
    "*Can we anyhow console val which corresponds to counter1 and counter2?*" - you [could once](https://stackoverflow.com/q/70718302/1048572), but [not any longer](https://stackoverflow.com/q/75016334/1048572). Now the only way is to place a breakpoint in `getVal` and call it. – Bergi Jan 14 '23 at 22:34
  • 3
    `What would be the right way to dispose it` - it is automatically garbage collected in a similar way other variables inside a function are disposed of. When you delete the variables `counter1` and `counter2` or assign some other values to them (eg. `counter1 = 'hello'`) the memory used by `val` attached to them gets garbage collected. – slebetman Jan 14 '23 at 23:21

0 Answers0