This content originally appeared on DEV Community and was authored by Nevin Katz
Hi everyone,
The concept of the closure is one of the tougher concepts for me when I first started learning JavaScript in depth. If you are new to the concept, a closure is essentially a function bundled together with its surrounding state, which typically includes variables that the closure needs. A closure is typically a function within a larger function, which serves as a "bubble." All the variables within this larger function bubble are only accessible by methods in the closure.
The JavaScript engine is smart enough to realize that the variables are needed, so the engine's garbage collector does not obliterate them.
Below is a quick example of a closure with four methods: get
, set
, increment
, and reset
. They all act on a variable called count
, which sits within the immediately invoked function expression (IIFE) holding the closure.
the
get
method will simply get thecount
value.the
set
method sets thecount
value to any value we want.the
increment
method will increment the existing value by the amount passed in as a parameter. If no value is passed in, it increments the value by 1.the
reset
method resets the value to zero.
These methods are the only way the user can access the count
value. In this way, the use of a closure causes the count
value to act in a similar way to that of a private variable in a Java object; it cannot be accessed outside the object, so methods are required to retrieve its value or update it.
In the demo, you will see that an init
method grabs some references to the HTML elements we print to and then calls all the methods. Take a look at how they are called and see if you can understand what causes these particular values to be printed out.
I hope this quick post gives you a solid idea of what closures are about. Thanks for reading!
This content originally appeared on DEV Community and was authored by Nevin Katz
Nevin Katz | Sciencx (2021-08-02T00:51:07+00:00) An Example of a Closure in JavaScript. Retrieved from https://www.scien.cx/2021/08/02/an-example-of-a-closure-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.