Closures are widely used in event listeners to make sure that handlers have access to variables defined in their outer scope. This allows developers to bind dynamic data to events without exposing the variables globally.
In this above code, each time the button is clicked, the event listener's callback function retains access to the clickCount
variable, even though setupButton
has finished execution. This make sure that the clickCount
value persists across multiple button clicks, thanks to the closure.