Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to create a private variable in JavaScript?
JavaScript doesn't have built-in private variables like other languages, but several techniques can simulate privacy. Each approach has its own benefits and use cases.
Private variables can only be accessed and modified by code within the same scope, while public variables are accessible from anywhere. Let's explore different techniques to create private variables in JavaScript.
Using Closures
Closures are the most common way to create private variables. A closure allows inner functions to access variables from their outer function scope, even after the outer function has finished executing.
<html>
<body>
<div id="demo"></div>
<script>
function createPrivateVariable() {
let privateVariable = "This is a private variable";
return {
getValue: function () {
return privateVariable;
},
setValue: function (value) {
privateVariable = value;
}
};
}
let privateVar = createPrivateVariable();
document.getElementById("demo").innerHTML = privateVar.getValue();
</script>
</body>
</html>
This is a private variable
The createPrivateVariable function returns an object with getValue and setValue methods. These methods can access privateVariable through closure, but the variable itself cannot be accessed directly from outside.
Using Symbol Data Type
Symbols are unique identifiers that can be used as property keys. They provide a level of privacy since they're not easily discoverable.
<html>
<body>
<div id="demo"></div>
<script>
let privateVar = Symbol('private');
let obj = {
[privateVar]: "This is a private variable",
getValue: function() {
return this[privateVar];
},
setValue: function(value) {
this[privateVar] = value;
}
};
document.getElementById("demo").innerHTML = obj.getValue();
</script>
</body>
</html>
This is a private variable
While the Symbol property isn't truly private (it can be accessed via Object.getOwnPropertySymbols()), it's hidden from normal enumeration and accidental access.
Using WeakMaps
WeakMaps provide true privacy by storing private data outside the object itself. The garbage collector automatically cleans up entries when objects are no longer referenced.
<html>
<body>
<div id="demo"></div>
<script>
let privateData = new WeakMap();
function MyClass(initialValue) {
privateData.set(this, { value: initialValue });
}
MyClass.prototype.getValue = function() {
return privateData.get(this).value;
};
MyClass.prototype.setValue = function(newValue) {
privateData.get(this).value = newValue;
};
let obj = new MyClass("This is a private variable");
document.getElementById("demo").innerHTML = obj.getValue();
</script>
</body>
</html>
This is a private variable
The private data is stored in the WeakMap and can only be accessed through the object instance. This provides true encapsulation.
Using Class Private Fields
Modern JavaScript supports private fields using the # syntax. This is now widely supported in modern browsers and provides true privacy.
<html>
<body>
<div id="demo"></div>
<script>
class MyClass {
#privateVariable = "This is a private variable";
getValue() {
return this.#privateVariable;
}
setValue(value) {
this.#privateVariable = value;
}
}
let obj = new MyClass();
document.getElementById("demo").innerHTML = obj.getValue();
// This would throw an error:
// console.log(obj.#privateVariable); // SyntaxError
</script>
</body>
</html>
This is a private variable
Private fields declared with # are truly private and cannot be accessed from outside the class, even with reflection techniques.
Using Proxy Objects
Proxies can intercept property access and create controlled access to variables.
<html>
<body>
<div id="demo"></div>
<script>
function createPrivateProxy() {
let privateVariable = "This is a private variable";
return new Proxy({}, {
get: function(target, prop) {
if (prop === 'getValue') {
return () => privateVariable;
}
if (prop === 'setValue') {
return (value) => { privateVariable = value; };
}
return undefined;
},
set: function(target, prop, value) {
// Prevent direct assignment
return false;
}
});
}
let obj = createPrivateProxy();
document.getElementById("demo").innerHTML = obj.getValue();
</script>
</body>
</html>
This is a private variable
The Proxy intercepts property access and only allows controlled access to the private variable through designated methods.
Comparison
| Method | True Privacy | Browser Support | Performance |
|---|---|---|---|
| Closures | Yes | Universal | Good |
| Symbols | Partial | ES6+ | Good |
| WeakMaps | Yes | ES6+ | Good |
| Private Fields | Yes | Modern browsers | Excellent |
| Proxies | Yes | ES6+ | Slower |
Conclusion
For modern applications, use class private fields with # syntax. For broader compatibility, closures remain the most reliable approach. Choose the method that best fits your browser support requirements and use case.
