In JavaScript, a private variable is a variable that is not accessible directly from outside the object/class where it is defined. Private variables help enforce encapsulation, meaning internal details are hidden, and only controlled access is allowed.
JavaScript didn’t originally have native private variables, but now (ES2022+) it supports true private fields using #. Before that, developers used closures or naming conventions (_variable) to simulate privacy.
1. Using # (Native Private Fields)
class User {
#password; // private variable
constructor(username, password) {
this.username = username;
this.#password = password;
}
// public method to access private data
checkPassword(input) {
return this.#password === input;
}
}
const user = new User("Himanshu", "12345");
console.log(user.username); // ✅ Himanshu
console.log(user.#password); // ❌ SyntaxError: Private field '#password' must be declared
console.log(user.checkPassword("12345")); // ✅ true
✅ The #password variable is truly private. It cannot be accessed outside the class.
2. Using Closures (Pre-ES2022 Way)
function createCounter() {
let count = 0; // private variable (closure)
return {
increment() { count++; },
getCount() { return count; }
};
}
const counter = createCounter();
counter.increment();
console.log(counter.getCount()); // ✅ 1
console.log(counter.count); // ❌ undefined (private)
Here, count is private because it’s only accessible inside the closure, not directly outside.
3. Using WeakMaps (Another Old Approach)
const _salary = new WeakMap();
class Employee {
constructor(name, salary) {
this.name = name;
_salary.set(this, salary);
}
getSalary() {
return _salary.get(this);
}
}
const emp = new Employee("John", 50000);
console.log(emp.name); // ✅ John
console.log(emp.getSalary()); // ✅ 50000
console.log(emp._salary); // ❌ undefined
WeakMap ties the private data to the object without exposing it.
🔑 Summary
- Private variables in JavaScript are mainly for data hiding.
- Modern way: Use
#privateFieldin classes. - Old ways: Use closures or
WeakMap. - Public methods can control access to private data.
