Q1. What is encapsulation?
Encapsulation is the process of wrapping data (variables) and methods (functions) together into a single unit, usually inside a class, and restricting direct access to some of the object's components.
Encapsulation helps protect data from being modified accidentally and ensures controlled access through methods. It is one of the core concepts of Object-Oriented Programming (OOP).
Encapsulation helps protect data from being modified accidentally and ensures controlled access through methods. It is one of the core concepts of Object-Oriented Programming (OOP).
Q2. Why is Encapsulation important in JavaScript?
Encapsulation is important because it improves code security, maintainability, and modularity.
It prevents direct access to sensitive data and allows developers to control how data is accessed or modified. This helps reduce bugs and makes code easier to manage.
It prevents direct access to sensitive data and allows developers to control how data is accessed or modified. This helps reduce bugs and makes code easier to manage.
Q3. How can Encapsulation be implemented in JavaScript?
Encapsulation can be implemented using classes, closures, and private properties.
Modern JavaScript provides private fields using the # symbol, which prevents direct access from outside the class.
Example
Modern JavaScript provides private fields using the # symbol, which prevents direct access from outside the class.
Example
class BankAccount { #balance;
constructor(balance) { this.#balance = balance; }
deposit(amount) { this.#balance += amount; }
getBalance() { return this.#balance; }}
const account = new BankAccount(1000);account.deposit(500);console.log(account.getBalance());Q4. What are private properties in JavaScript?
Private properties are variables that cannot be accessed directly from outside the class. They are declared using the # symbol.
They help in protecting sensitive data and enforce data hiding.
Example
They help in protecting sensitive data and enforce data hiding.
Example
class User { #password;
constructor(password) { this.#password = password; }
checkPassword(pass) { return this.#password === pass; }}Q5. What is data hiding in Encapsulation?
Data hiding is the concept of restricting direct access to internal data of an object.
The data can only be accessed or modified through public methods. This ensures that the data remains safe and valid.
The data can only be accessed or modified through public methods. This ensures that the data remains safe and valid.
