Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda