Encapsulation

Introduction
Encapsulation is a fundamental concept in object oriented programming. It refers to the practice of bundling data and the methods that operate on that data into a single unit such as an object. It also restricts direct access to some parts of the object to protect the data from unintended changes.

Core Concept
Encapsulation helps you control how data is accessed and modified. Instead of allowing direct access to variables, you use methods to interact with them. This improves security, flexibility, and maintainability of code.

Why Encapsulation is Important
Encapsulation protects sensitive data from accidental modification
It improves code organization and readability
It allows controlled access through functions
It makes applications easier to maintain and update

Encapsulation in JavaScript
In JavaScript, encapsulation can be achieved using functions, closures, and classes. Modern JavaScript also provides private fields using the hash symbol.

Example Using Class

class Person {
#name;

constructor(name) {
this.#name = name;
}

getName() {
return this.#name;
}

setName(newName) {
this.#name = newName;
}
}

const person1 = new Person("Ali");
console.log(person1.getName());

person1.setName("Ahmed");
console.log(person1.getName());

Explanation
The variable name is private and cannot be accessed directly from outside the class
The methods getName and setName are used to access and modify the value safely

Real World Example
Think of a bank account. You cannot directly access your balance variable. Instead, you use methods like deposit and withdraw. This ensures proper validation and security.

Benefits of Encapsulation
Improves data security
Reduces complexity in large applications
Enhances code reusability
Allows better debugging and testing

Best Practices
Always keep sensitive data private
Use getter and setter methods for controlled access
Avoid exposing internal object details directly

Conclusion
Encapsulation is a key principle that helps developers write secure and organized code. By controlling how data is accessed, it ensures better reliability and maintainability in JavaScript applications.

Home ยป Professional JavaScript > OOP in JavaScript > Encapsulation