Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

163
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda