---
title: "How can you achieve encapsulation in JavaScript?"  
description: "How can you achieve encapsulation in JavaScript?"  
author: "Sandra Emily"  
published: 2023-10-08  
updated: 2023-10-09  
canonical: https://www.mindstick.com/forum/160069/how-can-you-achieve-encapsulation-in-javascript  
category: "javascript"  
tags: ["javascript", "oops"]  
reading_time: 3 minutes  

---

# How can you achieve encapsulation in JavaScript?

How can you achieve [encapsulation](https://www.mindstick.com/articles/12229/encapsulation-and-access-specifier) in [JavaScript](https://www.mindstick.com/articles/874/how-to-create-watermark-text-for-textbox-by-using-javascript)?

## Replies

### Reply by Aryan Kumar

In JavaScript, encapsulation can be achieved through a combination of closures and object-oriented programming techniques. Encapsulation is the concept of bundling the data (attributes) and the methods (functions) that operate on the data into a single unit, which is an object. It also involves controlling access to the internal state of an object to ensure data integrity. Here's how you can achieve encapsulation in JavaScript:

## Private Properties and Methods:

- JavaScript doesn't have native support for access control keywords like **private**, **public**, or **protected** as some other languages do. However, you can emulate private properties and methods using closures.
- Define variables or functions within the constructor or a factory function, and they will be accessible only within that scope.

```plaintext
function Person(name) {
  let _name = name; // Private variable

  function _getFullName() { // Private method
    return _name;
  }

  this.sayHello = function() {
    console.log(`Hello, my name is ${_getFullName()}`);
  };
}

const person = new Person("Alice");
console.log(person._name); // undefined (private variable)
person.sayHello(); // Outputs: "Hello, my name is Alice"
```

## Getter and Setter Methods:

- Use getter and setter methods to access and modify private properties while controlling their access.
- This allows you to validate and manage the data before it's read or modified.

```plaintext
function BankAccount() {
  let _balance = 0;

  this.getBalance = function() {
    return _balance;
  };

  this.deposit = function(amount) {
    if (amount > 0) {
      _balance += amount;
    } else {
      console.log("Invalid deposit amount.");
    }
  };

  this.withdraw = function(amount) {
    if (amount > 0 && amount <= _balance) {
      _balance -= amount;
    } else {
      console.log("Invalid withdrawal amount or insufficient balance.");
    }
  };
}

const account = new BankAccount();
account.deposit(1000);
console.log(account.getBalance()); // Outputs: 1000
account.withdraw(500);
console.log(account.getBalance()); // Outputs: 500
```

## Use ES6 Classes:

- With the introduction of ES6 classes, you can achieve encapsulation by defining private properties and methods using the **_** convention.
- While these properties and methods are not truly private, the **_** convention signals to other developers that they are intended to be treated as private.

```plaintext
class Rectangle {
  constructor(width, height) {
    this._width = width; // Private property
    this._height = height; // Private property
  }

  area() {
    return this._width * this._height; // Public method
  }
}

const rect = new Rectangle(5, 10);
console.log(rect._width); // 5 (though it's meant to be private)
console.log(rect.area()); // Outputs: 50
```

Remember that JavaScript does not provide strict access control like some other languages, so encapsulation in JavaScript relies on conventions and the use of closures and getter/setter methods to create private and controlled access to properties and methods.


---

Original Source: https://www.mindstick.com/forum/160069/how-can-you-achieve-encapsulation-in-javascript

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
