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
How exactly is count getting incremented with every button click here?

I would love to understand how exactly closure happens in this set of code and the way its implemented. I was watching a tutorial and the guy was giving example on callback function and he also gave example of closure there.

function attachEventListeners() {
    let count = 0
    document.getElementById("clickMe").addEventListener("click", function () {
        console.log("Button Clicked", ++count)
    })
attachEventListeners()

I thought in order for a closure-based count function to work, you had to return that function and assign it to a variable. Cause otherwise with each call of the outer function, count would initialize to 0. But how is it working here?

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

Closure is essentially a case of when a function inside of another function reaches outside of its own scope to grab variables that are in the scope of the outer function.

function attachEventListeners() {
    let count = 0
    document.getElementById("clickMe").addEventListener("click", function () {
        console.log("Button Clicked", ++count)
    })

In this example, the anonymous function handed to the event listener is grabbing and incrementing the variable count in the attachEventListeners function scope.

about 4 years ago · Juan Pablo Isaza Denunciar

0

It is returning a new function to the listener every time, but each time you're attaching a new listener to the button which is silly.

Add one listener to the button. Call the handler which will return the closure as the function that will be called when the listener is fired.

const button = document.getElementById('clickMe');

// Call the handler that returns a function (your closure)
// that acts as the the listener. It only needs to be called once.
button.addEventListener('click', handler(), false);

function handler() {

  let count = 0;

  // The closure contains, and updates, the variable in
  // its local environment when it's returned
  return function () {
    console.log('Button Clicked', ++count);
  };
};
<button id="clickMe">Click me</button>

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