Encapsulation
What is Encapsulation?
Encapsulation is one of the core principles of Object-Oriented Programming. It is the concept of bundling data (properties) and methods that operate on that data into a single unit (the class), and restricting direct access to some of the object's components.
Think of an ATM machine. You interact with the screen and the keypad (the public interface), but the money vault and the internal computer are locked away (encapsulated) so you cannot tamper with them directly.
Private Fields in JavaScript
Historically, JavaScript developers used an underscore (_) before a property name (e.g., this._balance) to signal that a property was "private" and shouldn't be touched. However, this was just a naming convention; the property could still be modified.
Modern JavaScript introduced true private class fields using the # symbol.
class BankAccount {
// Declare a private field using #
#balance;
constructor(initialBalance) {
this.#balance = initialBalance;
}
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
console.log(`Deposited ${amount}.`);
}
}
getBalance() {
return this.#balance;
}
}
const himanshuAccount = new BankAccount(100);
himanshuAccount.deposit(50);
console.log(himanshuAccount.getBalance()); // 150
// Trying to access the private field directly will cause a Syntax Error!
// console.log(himanshuAccount.#balance); // Error!
Getters and Setters
To safely read or update encapsulated data, we often use get and set methods. These look like methods but are accessed like properties.
class User {
#password;
constructor(password) {
this.#password = password;
}
// Setter to safely change the password
set updatePassword(newPassword) {
if (newPassword.length >= 8) {
this.#password = newPassword;
} else {
console.log("Password too short!");
}
}
}
const user1 = new User("12345678");
user1.updatePassword = "new"; // Outputs: "Password too short!"
💡 Himanshu's Tip:
Always encapsulate data that shouldn't be randomly changed by other parts of your program. If a variable is crucial to the internal logic of your class (like the state of a game engine or a user's password), lock it down with a #!
Interview Questions
- What does the term "Encapsulation" mean in OOP?
- How do you create a truly private class field in modern JavaScript?
- What is the difference between a normal method and a
getter/settermethod?