Closure Question

Hey,

In the code below, why do we need to create counter from counterCreator? Why doesn’t calling counterCreator() work?

Thanks

const counterCreator = () => {
    let count = 0;
    return () => {
      console.log(count);
      count++;
    };
};

const counter = counterCreator();

counter();
counter();
counter();

counterCreator returns function, which counts with closure. To make it count once, in theory it could be called counterCreator()(), but the function wouldn’t be assigned to any variable, and there wouldn’t be any way to make it count furhter.

On the other hand, every time counterCreator() is called, it returns fresh counter function, which allows for multiple, independent counters:

const counter1 = counterCreator();
const counter2 = counterCreator();

counter1() // 0
counter1() // 1
counter1() // 2
counter2() // 0
counter1() // 3
1 Like

Thanks for responding! After asking ChatGPT multiple questions, I think I found what I was getting at. From what I understand, once the outer-function runs, it gets ‘cleaned up’ by the garbage collector, so whenever it 's run it’s created all over again, creating a NEW inner-function, which only has access to the NEW ‘count’ variable and not the old one.

When we set the variable equal to the outer function, the variable holds a reference to the inner function, along with it’s closure, and therefore, still retains access to the ‘count’ variable, after the outer-function has been ‘cleaned up’.

Is there anything I’m missing or getting wrong here? Thanks!

I’m not chat, but I don’t think it’s that much garbage collector related. It’s not even certain that garbage collector will run before counterCreator will be called again and adding garbage collection to the equation can this more complicated.

As the function returned from counterCreator uses the count variable, it is enclosed with the returned function as a closure. It’s true that counterCreator function doesn’t keep any reference to the returned function or count variable. But that’s true for most of the functions. ie.:

function add(y) {
    const x = 0;
    return x + y;
}

Generally, unless function refers to some external variables, it doesn’t keep the changed state between the function calls.

const counter = counterCreator();
counter() // 0
counter() // 1

After this the counterCreator functions is still the:

const counterCreator = () => {
    let count = 0;
    return () => {
      console.log(count);
      count++;
    };
};
1 Like

Got it! Thanks for your help!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.