How to Use Closures for Data Privacy
How to leverage lexical scope to create private variables that cannot be manipulated globally.
Understand the Goal
JavaScript traditionally lacks true private variables. If you attach a counter to the global window object, any script can maliciously alter the count. You must hide it.
Wrap State in an Outer Function
Create an outer function (e.g., function createCounter()). Inside it, declare your state variable (e.g., let count = 0;). Because it is inside a function, it is completely invisible to the global scope.
Create the Inner Function
Inside the outer function, create an inner function (e.g., function increment()). Inside this inner function, modify the 'count' variable (count++).
Return the Inner Function
The outer function must return the inner function. When you do this, you are returning a Closure: the inner function bundled together with a live reference to the 'count' variable.
Instantiate the Closure
In the global scope, call the outer function and assign the result to a variable: const myCounter = createCounter().
Observe the Privacy
You can now call myCounter() to increment the value safely. However, it is physically impossible for the global scope to type console.log(count) or count = 999. The data is securely encapsulated.
Ready to master this completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.

