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

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

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 Relatório

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 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