A closure is a combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function’s scope from an inner function.
Example: Here the inner forms closure with outer. The str variable can be called a private member whose value we can access, but not modify directly.
The concept of a private counter means that publicly/globally we could not modify the counter variable directly. The below step-by-step guide will teach you how to implement a private counter with closure and understand it.
Step 1: Create counter.js and index.html files. You can give any allowed names to the files.
Step 2: First begin with the index.html file and create a front-end to see the counter. We would create a <div> to show the value of the counter and two buttons, one for incrementing and the other for decrementing the counter.
Step 3: Let’s now work with the counter.js file and implement behind-the-scenes functions.
When the buttons get clicked counterHandler is called, we get the value of the button from objButton Object. If the value is one (1) then to be incremented else to be decremented the value of the counter which is count variable.
In the counter function, we have a counter variable count, increment function to increment, and decrement function to decrement the value by one. The modify function is returned as closure to the global when the counter function is called and we store its instance in closure constant.
Finally, we modify the div content to the value of the counter returned by closure using its innerHTML property.
Step 3: Copy the full path of the HTML index.html file and paste it into any browser. After loading the HTML file in the browser, you would see something similar to it. Now play with the increment and decrement buttons and observe the value of counter changing.
Now let’s see what happens in the backend using Developers Tool when the button is clicked. In the below image we had made the counter value equals -1. To see how the scope is defined and related to it.