• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

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

almost 3 years ago · Juan Pablo Isaza
2 answers
Answer question

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.

almost 3 years ago · Juan Pablo Isaza Report

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>

almost 3 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 Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error