Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!