🛡️ Encapsulation in JavaScript (OOP)

Last Updated: 24th October 2025


Encapsulation is the concept of wrapping data (properties) and methods together inside a class and controlling access to them.
It is one of the core principles of OOP, alongside Inheritance, Polymorphism, and Abstraction.

Hinglish Tip 🗣: Encapsulation ko samjho jaise ek capsule — andar sab cheezein secure hain aur bahar se direct touch nahi kar sakte. Sirf class ke through hi access kar sakte ho.


Why Use Encapsulation?

  1. Protect sensitive data (e.g., passwords, bank balance).
  2. Control how data is accessed or modified.
  3. Reduce bugs by hiding internal implementation.
  4. Maintain a clean interface for other developers.

🧩 Implementation in JavaScript

JavaScript supports encapsulation using:

  1. Private fields (#)
  2. Getter and Setter methods
  3. Convention-based protected fields (_)

1. Private Fields with #

class BankAccount {
  #balance = 5000; // private field

  deposit(amount) {
    if (amount > 0) {
      this.#balance += amount;
    }
  }

  withdraw(amount) {
    if (amount > 0 && amount <= this.#balance) {
      this.#balance -= amount;
    }
  }

  showBalance() {
    console.log(`Balance: ${this.#balance}`);
  }
}

const acc = new BankAccount();
acc.deposit(1000);
acc.withdraw(500);
acc.showBalance(); // ✅ Balance: 5500
// console.log(acc.#balance); ❌ Error: Private field '#balance' must be declared

Hinglish Tip 🗣: #balance ko bahar se access karne ki koshish mat karo — sirf class ke methods se interact karna hai.


2. Getter & Setter

  • Getters allow reading private values.
  • Setters allow controlled modification.
class Person {
  #name;

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

  // Getter
  getName() {
    return this.#name;
  }

  // Setter
  setName(newName) {
    if (newName.length >= 3) {
      this.#name = newName;
    } else {
      console.log("Name too short");
    }
  }
}

const p = new Person("Riya");
console.log(p.getName()); // ✅ Riya
p.setName("Jo"); // ❌ Name too short
p.setName("Anita"); // ✅ Works
console.log(p.getName()); // ✅ Anita

Hinglish Tip 🗣: Getters/Setters ek filter jaisa hai — validation aur control ka.


3. Protected Fields by Convention

  • Fields with _ are considered protected by convention.
  • Can be accessed in subclass but should not be accessed externally.
class Employee {
  constructor(name, salary) {
    this.name = name;
    this._salary = salary; // protected by convention
  }
}

class Manager extends Employee {
  showSalary() {
    console.log(`${this.name}'s Salary: ${this._salary}`);
  }
}

const m = new Manager("Amit", 50000);
m.showSalary(); // ✅ Amit's Salary: 50000
console.log(m._salary); // ⚠️ Works, but not recommended

Hinglish Tip 🗣: _salary ek hint hai — “use carefully, main protected hu.”