An Example of a Closure in JavaScript
Nevin Katz
Posted on August 2, 2021
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 an object with four functions that are actually closures.
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.
Each function, which comes bundled with its surrounding environment, is a 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!
Elsewhere
For a tutorial on closures with an easy on-ramp, check out JavaScript Closures and Their Scope Bubbles on Medium.
Posted on August 2, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 28, 2024
November 27, 2024