- Courses
- đ»Programming Languages
- đJavaScript
- Objects and Classes
- Encapsulation & Private Fields
On this page
Encapsulation and Private Fields
By Enrico Hochkoeppler
Web Developer & TutoriaLibre Founder
Encapsulation is one of the four fundamental pillars of Object-Oriented Programming (OOP). It is the practice of bundling data (properties) and the methods that operate on that data into a single unit, while simultaneously restricting direct access to some of the object's components. In modern JavaScript, this is achieved through Private Fields, denoted by the hash # prefix.
The Concept of Encapsulationâ
The primary goal of encapsulation is to hide the internal state of an object and require all interaction to happen through a well-defined interface (public methods). This prevents "external" code from accidentally or intentionally corrupting the internal logic of your object, ensuring that the object remains in a valid state.
Implementing Private Fields withâ
Historically, JavaScript developers used an underscore prefix (e.g., _password) as a convention to signal that a property was intended to be private. However, this was merely a "gentleman's agreement" and did not provide actual technical protection.
The introduction of Private Class Fields (using the # symbol) provides true, engine-level privacy. When a property name starts with #, it is completely inaccessible from outside the class.
Syntax and Declarationâ
Private fields must be declared at the top level of the class body before they are used. They cannot be created dynamically on the fly.
class BankAccount {
// Declaring a private field
#balance;
constructor(initialDeposit) {
this.#balance = initialDeposit;
}
getBalance() {
return `Your balance is $${this.#balance}`;
}
}
const myAccount = new BankAccount(1000);
console.log(myAccount.getBalance()); // Output: Your balance is $1000
// console.log(myAccount.#balance); // Syntax Error: Private field '#balance' must be declared in an enclosing class
Controlled Access with Getters and Settersâ
To allow external code to interact with private data safely, we use Getters and Setters. These are special methods that look like properties but allow you to execute logic during the reading or writing process.
- Getter: Used to retrieve the value, often after formatting it.
- Setter: Used to update the value, allowing for validation before the change is applied.
class User {
#age;
constructor(age) {
this.#age = age;
}
// Getter
get age() {
return `${this.#age} years old`;
}
// Setter with validation logic
set age(newValue) {
if (newValue > 0 && newValue < 120) {
this.#age = newValue;
} else {
console.error("Invalid age provided.");
}
}
}
const person = new User(25);
person.age = 30; // Calls the setter
console.log(person.age); // Calls the getter: "30 years old"
Private Methodsâ
Just as data can be private, logic can also be hidden. If a class has a complex internal process that should not be exposed to the user of the class, you can define a Private Method using the same # prefix.
class SecureSystem {
#generateKey() {
return Math.random().toString(36).substring(2);
}
getAccess() {
const key = this.#generateKey(); // Internal logic is hidden
console.log(`Access granted with key: ${key}`);
}
}
const sys = new SecureSystem();
sys.getAccess();
// sys.#generateKey(); // Error: Method is private
Benefits of Encapsulationâ
- Data Integrity: By using setters, you can validate data before it is saved, preventing "impossible" states (like a negative bank balance).
- Simplified Interface: Users of your class only see the methods they need, reducing the complexity of the API.
- Future-Proofing: You can change the internal implementation (e.g., changing how
#balanceis calculated) without breaking any external code that relies on the publicgetBalance()method.
Professional Rules for Privacyâ
- Default to Private: If a property doesn't need to be accessed from outside, make it private. This follows the Principle of Least Privilege.
- Validation in Setters: Always use setters to protect your objectâs state from invalid inputs.
- Shadowing and Inheritance: Note that private fields are not accessible even in subclasses. If an
Employeeclass extends aPersonclass, theEmployeecannot directly access the#ssnfield of thePerson. Access must be granted via public or protected methods.
Found this helpful? Share the knowledge...
... or support this project to keep it alive!
Previous
Classes
Next
Core Objects
-
The Concept of Encapsulation
-
Implementing Private Fields with
- Syntax and Declaration
-
Controlled Access with Getters and Setters
-
Private Methods
-
Benefits of Encapsulation
-
Professional Rules for Privacy
