Encapsulation in JavaScript
Last Updated :
10 Jan, 2024
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.
Encapsulation can be achieved using two techniques:
Using Closures
In JavaScript, closures are functions that have access to variables in their outer lexical environment, even after the outer function has returned. Private variables and methods can be created using closures.
Example: In this example, we have created a BankAccount object using a closure. The object has three private variables: _accountNumber, _accountHolderName, and _balance. These variables are only accessible within the BankAccount 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.
JavaScript
function BankAccount(accountNumber, accountHolderName, balance) {
let _accountNumber = accountNumber;
let _accountHolderName = accountHolderName;
let _balance = balance;
function showAccountDetails() {
console.log(`Account Number: ${_accountNumber}`);
console.log(`Account Holder 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 myBankAccount = BankAccount("123456", "John Doe", 1000);
myBankAccount.deposit(500);
// Output: Account Number: 123456 Account Holder Name:
//John Doe Balance: 1500
myBankAccount.withdraw(2000); // Output: Insufficient Balance
OutputAccount Number: 123456
Account Holder Name: John Doe
Balance: 1500
Insufficient Balance
Using Classes
ES6 introduced the class syntax in JavaScript, which allows us to define classes and objects in a more structured way. Classes can be used to achieve encapsulation in JavaScript.
Example: In this example, we have created a BankAccount class using the class keyword. The class has three private variables: _accountNumber, _accountHolderName, and _balance. These variables are prefixed with an underscore to indicate that they are private variables. The showAccountDetails method is a public method that displays the account details. The deposit and withdrawal methods are also public methods that can be accessed from outside the object. When these methods are called, they update the _balance variable and call the showAccountDetails method to display the updated account details.
JavaScript
class BankAccount {
constructor(accountNumber, accountHolderName, balance) {
this._accountNumber = accountNumber;
this._accountHolderName = accountHolderName;
this._balance = balance;
}
showAccountDetails() {
console.log(`Account Number: ${this._accountNumber}`);
console.log(`Account Holder 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 myBankAccount = new BankAccount("123456", "John Doe", 1000);
myBankAccount.deposit(500);
// Output: Account Number: 123456 Account Holder Name:
//John Doe Balance: 150
OutputAccount Number: 123456
Account Holder Name: John Doe
Balance: 1500
Benefits of encapsulation in JavaScript:
- Data Security: Encapsulation helps in protecting the data by preventing direct access to private variables. This ensures that the data is not modified inappropriately.
- Code Reusability: Encapsulation makes it easier to reuse code since objects are self-contained and can be used in different parts of the application.
- Maintenance: Encapsulation makes it easier to maintain the code since objects are independent of each other and changes made to one object do not affect the others.
Conclusion: Encapsulation is an important concept in object-oriented programming, and JavaScript supports encapsulation using closures and classes. Encapsulation helps in maintaining the integrity of data, improving code reusability, and making code maintenance easier. As a JavaScript developer, it is important to understand how encapsulation works and to use it effectively in your code.
Similar Reads
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q
15+ min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
CSS Tutorial CSS stands for Cascading Style Sheets. It is a stylesheet language used to style and enhance website presentation. CSS is one of the three main components of a webpage, along with HTML and JavaScript.HTML adds Structure to a web page.JavaScript adds logic to it and CSS makes it visually appealing or
7 min read
Node.js Tutorial Node.js is a powerful, open-source, and cross-platform JavaScript runtime environment built on Chrome's V8 engine. It allows you to run JavaScript code outside the browser, making it ideal for building scalable server-side and networking applications.JavaScript was mainly used for frontend developme
4 min read
HTML Introduction HTML stands for Hyper Text Markup Language, which is the core language used to structure content on the web. It organizes text, images, links, and media using tags and elements that browsers can interpret. As of 2025, over 95% of websites rely on HTML alongside CSS and JavaScript, making it a fundam
6 min read