🛡️ Abstraction in JavaScript (OOP)

Last Updated: 24th October 2025


Abstraction means hiding the internal details of a class and showing only the necessary functionalities to the user.

Hinglish Tip 🗣: Jaise car chalana hai, aapko engine ka pura kaam samajhne ki zarurat nahi. Sirf start(), accelerate(), brake() methods use karte ho. Yehi hai abstraction.


How to Achieve Abstraction in JS

  1. Using Classes and Methods
  2. Using private properties (#)
  3. Exposing only necessary methods

1. Example: Hiding Internal Data

class BankAccount {
  #balance; // private property

  constructor(initialBalance) {
    this.#balance = initialBalance;
  }

  deposit(amount) {
    this.#balance += amount;
    console.log(`Deposited ${amount}. Current Balance: ${this.#balance}`);
  }

  withdraw(amount) {
    if (amount <= this.#balance) {
      this.#balance -= amount;
      console.log(`Withdrew ${amount}. Current Balance: ${this.#balance}`);
    } else {
      console.log("Insufficient balance!");
    }
  }

  getBalance() {
    console.log(`Balance is ${this.#balance}`);
  }
}

const acc = new BankAccount(1000);
acc.deposit(500); // Deposited 500. Current Balance: 1500
acc.withdraw(200); // Withdrew 200. Current Balance: 1300
acc.getBalance(); // Balance is 1300

// Trying to access private property
console.log(acc.#balance); // SyntaxError

Hinglish Tip 🗣: #balance ko directly access nahi kar sakte → hidden from user. Only deposit, withdraw, getBalance are accessible → abstraction.


2. Abstract Classes (Simulated)

JS doesn't have true abstract classes, but we can throw error in base class to simulate.

class Vehicle {
  start() {
    throw new Error("Method 'start()' must be implemented.");
  }
}

class Car extends Vehicle {
  start() {
    console.log("Car started!");
  }
}

const myCar = new Car();
myCar.start(); // Car started!

const v = new Vehicle();
v.start(); // Error: Method 'start()' must be implemented.

Hinglish Tip 🗣: Base class ka method define karte hain but force karte hain child class implement kare → abstraction simulation.


💡 Quick Practice

  • Create Employee class with private property salary.
  • Add public methods setSalary(), getSalary().
  • Create Manager class extending Employee and test abstraction.
  • Exercise

Liked This Tutorial

Scan QR Code To Leave A Review Or

Click Here To Leave A Review
Scan QR