John Doe
John Doe

Reputation: 423

question about closure in js and wrong output

I am trying to understand the core of js concepts, and I tried to write some closure.

function counter(){

  let counter = 0;
  
  return{
    increment: () => counter++,
    getCounter:  counter
  }
}


const addCounter = counter();

addCounter.increment();
addCounter.increment();
addCounter.increment();
addCounter.increment();
addCounter.increment();

console.log(addCounter.getCounter)

the output here is 0 if I will change getCounter: counter to getCounter:()=>counter and will call again with addCounter.getCounter() the answer is correct and will be 5. can someone explain me why?

Upvotes: 0

Views: 42

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

When the object is returned, the content here is evaluated as an expression:

{
    increment: () => counter++,
    getCounter:  counter
}

At that point in time, the counter is 0, so it's equivalent to

{
    increment: () => counter++,
    getCounter: 0
}

The counter, although updated by the increment function, is not referenced again after the (static) object is returned.

You need to make getCounter a function or getter, so that it returns the current value inside the closure.

function counter(){

  let counter = 0;
  
  return{
    increment: () => counter++,
    get getCounter() { return counter; }
  }
}


const addCounter = counter();

addCounter.increment();
addCounter.increment();
addCounter.increment();
addCounter.increment();
addCounter.increment();

console.log(addCounter.getCounter)

Upvotes: 2

Related Questions