Closures and Data Privacy in JavaScript
Closures let you hide variables from the outside. Here is the module pattern and how to create private state.
Closures and Data Privacy in JavaScript
JavaScript does not have private variables on objects (until very recently with #private fields). Closures provide a way to create truly private state.
The Basic Pattern
function createCounter() { let count = 0; return { increment: () => ++count, decrement: () => --count, getCount: () => count, }; } const counter = createCounter(); counter.increment(); counter.increment(); counter.getCount(); // 2 // count is not accessible directly: counter.count; // undefined `` `count` is inside `createCounter`'s lexical environment. The returned methods close over it. The outside world can only interact with `count` through the methods. ### The Module Pattern ```js const myModule = (function () { const privateVar = "secret"; function privateMethod() { return privateVar.toUpperCase(); } return { publicMethod: () => privateMethod(), publicVar: "public", }; })(); myModule.publicMethod(); // "SECRET" myModule.privateVar; // undefined myModule.privateMethod; // undefined `` An IIFE creates a private scope. Only the returned object is accessible. This was the standard way to achieve modules before ES6. ### Encapsulation Closures provide **encapsulation**: hiding internal state and exposing only a controlled API. This is the same principle as private methods in classes: ```js class Counter { #count = 0; // truly private field (ES2022) increment() { return ++this.#count; } getCount() { return this.#count; } } `` `#private` fields are the modern way. Closures are the classic way. ### Data Hiding ```js function createUser(name) { let password = "default"; return { getName: () => name, setPassword: (newPwd) => { password = newPwd; }, authenticate: (pwd) => pwd === password, }; } const user = createUser("Kunal"); user.password; // undefined (hidden) user.authenticate("default"); // true user.authenticate("wrong"); // false `` `password` is completely hidden. It can only be set via `setPassword` and checked via `authenticate`. ### Advantages - **True privacy**: variables cannot be accessed or modified from outside. - **Controlled access**: only the returned API can interact with the state. - **No naming collisions**: each closure has its own private scope. ### Disadvantages - **Memory**: closed-over variables are not garbage collected until the closure is. - **Testing**: private state is harder to test (you must go through the API). - **Debugging**: you cannot inspect closed-over variables directly. ### The Takeaway Closures provide data privacy by hiding variables inside a function's lexical environment and exposing only a returned API. The module pattern (IIFE) was the classic approach. Modern JS has `#private` class fields, but closures are still widely used for private state.
By declaring variables inside a function and returning methods that access them. The variables are in the function's lexical environment and cannot be accessed directly from outside, only through the returned methods.
An IIFE that creates a private scope and returns an object with public methods. The private variables and methods are hidden inside the closure. Only the returned object is accessible from outside.
No. ES2022 introduced #private class fields, which are truly private on class instances. But closures are still widely used for private state in non-class contexts and were the standard before private fields existed.
Closed-over variables are not garbage collected until the closure is (memory cost), private state is harder to test (you must go through the API), and you cannot inspect closed-over variables during debugging.
Encapsulation is hiding internal state and exposing only a controlled API. Closures achieve this by keeping variables in a function's lexical environment and returning methods that interact with them. The outside world can only use the returned methods.
Ready to master React 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.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

