- Home
- /
- JS Encapsulation
JavaScript Tutorial
IINTRODUCTION
JAVASCRIPT VARIABLES
JAVASCRIPT BASICS
JAVASCRIPT OBJECTS
DOM & BOM
OOPs
- Home
- /
- JS Encapsulation
Encapsulation in JavaScript
Encapsulation is one of the core principles of object-oriented programming (OOP). It’s all about keeping the internal details of an object hidden from the outside world, and only exposing what’s necessary.
Think of it like a vending machine—you press a button to get a drink, but you don’t need to know what’s happening inside the machine. Similarly, in JavaScript, we can protect the internal logic of our objects using something called closures.
What Encapsulation Means in JavaScript
JavaScript doesn’t have traditional access modifiers like private
and protected
(like other languages such as Java or C#), but we can still achieve encapsulation using functions and closures.
Let’s look at a custom example from Learn With Arshyan:
function Student(name, marks) {
let privateMarks = marks;
this.name = name;
this.getMarks = function () {
return privateMarks;
};
this.setMarks = function (newMarks) {
if (newMarks >= 0 && newMarks <= 100) {
privateMarks = newMarks;
}
};
}
const student = new Student("Adeel", 85);
console.log(student.name); // Output: Adeel
console.log(student.privateMarks); // Output: undefined
console.log(student.getMarks()); // Output: 85
student.setMarks(92);
console.log(student.getMarks()); // Output: 92
How It Works
privateMarks
is not accessible directly because it’s a local variable inside the constructor function.The
getMarks
andsetMarks
methods act as controlled gateways to interact withprivateMarks
.We used a closure (a function that remembers its surrounding context) to hide the data.
This is encapsulation: hiding the data and exposing only the required interfaces.
Why Encapsulation Matters
Security: Prevents unwanted or accidental changes to important variables.
Cleaner Code: Keeps unrelated parts of the program from touching internal object logic.
Flexibility: Internal implementation can change without affecting other code that uses the object.
What About Modern JavaScript?
As of ECMAScript 2022, JavaScript supports private class fields using the #
symbol.
Example:
class BankAccount {
#balance = 0;
deposit(amount) {
if (amount > 0) {
this.#balance += amount;
}
}
getBalance() {
return this.#balance;
}
}
const account = new BankAccount();
account.deposit(500);
console.log(account.getBalance()); // Output: 500
console.log(account.#balance); // SyntaxError: Private field
The #balance
field is truly private and cannot be accessed outside the class—not even by mistake.
Final Thoughts
Encapsulation in JavaScript helps you keep your code clean, safe, and maintainable. You can achieve it through:
Closures (common and backward-compatible)
#
private fields (modern and native in classes)
By carefully choosing what to expose and what to keep hidden, you can write JavaScript code that is both powerful and reliable.