How to achieve encapsulation in JavaScript using closures or classes?
In this article, we will show you an example of codes that use encapsulation using both approaches, showcasing private variables and methods that maintain data integrity and ensure proper access control.
Are you ready to learn about keeping internal details hidden and providing clear and organized code? So let’s get started!
What is encapsulation in JavaScript?
Encapsulation is a concept in JavaScript that combines data and its related methods into one package.
This helps to control how this package is accessed. In JavaScript, you can achieve encapsulation either by using closures or private fields.
The advantage of encapsulation is that it allows you to separate the inner workings and implementation details of the package from how it’s used externally, creating a clearer and more organized code structure.
Moreover, encapsulation is a fundamental concept in object-oriented programming that refers to the practice of hiding the internal details of an object and exposing only the necessary information to the outside world.
How to use encapsulation in JavaScript?
In JavaScript, encapsulation can be achieved using two techniques: using closures and using classes.
Using closures, private variables, and methods can be created.
Here’s an example that demonstrates how encapsulation can be achieved in JavaScript using closure:
function GcashAccount(accountNumber, accountHolderName, balance) {
let _accountNumber = accountNumber;
let _accountHolderName = accountHolderName;
let _balance = balance;
function showAccountDetails() {
console.log(`Gcash Number: ${_accountNumber}`);
console.log(`Gcash Name: ${_accountHolderName}`);
console.log(`Balance: ${_balance}`);
}
function deposit(amount) {
_balance += amount;
showAccountDetails();
}
function withdraw(amount) {
if (_balance >= amount) {
_balance -= amount;
showAccountDetails();
} else {
console.log("Insufficient Balance");
}
}
return {
deposit: deposit,
withdraw: withdraw
};
}
let myGcashAccount = GcashAccount("143256423", "Itsourcecode", 10000);
myGcashAccount.deposit(500);
myGcashAccount.withdraw(10000);
As you can see, we made a GcashAccount object using a closure. This object has three private variables: _accountNumber, _accountHolderName, and _balance.
These variables are only accessible within the GcashAccount function and cannot be accessed from outside.
The showAccountDetails function is a private method that displays the account details. The deposit and withdrawal methods are public methods that can be accessed from outside the object.
When these methods are called, they update the _balance variable and call the showAccountDetails function to display the updated account details.
Output:
Gcash Number: 143256423
Gcash Name: Itsourcecode
Balance: 10500
Gcash Number: 143256423
Gcash Name: Itsourcecode
Balance: 500
Encapsulation can also be achieved using classes in JavaScript. ES6 introduced the class syntax in JavaScript, which allows us to define classes and objects in a more structured way.
Encapsulation helps maintain the integrity of data and ensures that it is not accessed or modified inappropriately.
It also provides benefits such as data security, code reusability, and easier maintenance.
Here’s another example that demonstrates how encapsulation can be achieved in JavaScript using classes:
class GcashAccount {
constructor(accountNumber, accountHolderName, balance) {
this._accountNumber = accountNumber;
this._accountHolderName = accountHolderName;
this._balance = balance;
}
showAccountDetails() {
console.log(`Gcash Number: ${this._accountNumber}`);
console.log(`Gcash Name: ${this._accountHolderName}`);
console.log(`Balance: ${this._balance}`);
}
deposit(amount) {
this._balance += amount;
this.showAccountDetails();
}
withdraw(amount) {
if (this._balance >= amount) {
this._balance -= amount;
this.showAccountDetails();
} else {
console.log("Insufficient Balance");
}
}
}
let myGcashAccount = new GcashAccount("143256423", "Itsourcecode", 500);
myGcashAccount.deposit(15000);
myGcashAccount.withdraw(1500);
Output:
Gcash Number: 143256423
Gcash Name: Itsourcecode
Balance: 15500
Gcash Number: 143256423
Gcash Name: Itsourcecode
Balance: 14000
This is another way to achieve encapsulation in JavaScript, by using classes to define objects and their properties and methods.
By making the properties private, we can ensure that they are only accessed and modified through the appropriate methods, providing an additional layer of security and maintainability.
Conclusion
In conclusion, this article discusses encapsulation in JavaScript, which is a powerful concept that combines data and related methods into a package, allowing for better control and organization of code.
It can be achieved using closures or classes. Closures enable the creation of private variables and methods, while classes provide a more structured approach to defining objects with private properties and public methods.
Encapsulation helps maintain data integrity, improves security, and enhances code reusability and maintainability, making your JavaScript code more robust and efficient.
We are hoping that this article provides you with enough information that help you understand how to use encapsulation in JavaScript.
You can also check out the following article:
Thank you for reading itsourcecoders 😊.