Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Updated
5 min read
Understanding Object-Oriented Programming in JavaScript

Blueprint banao, objects banao. Har error apni story rakhta hai.

You write code. Same pattern. Different data.

Ek error ka message alag. Doosre error ka stack alag.

Bar bar likhna? Nah.

OOP solves this.

Let me explain.


Real-World Analogy: Father → Children

A father has a name, values, responsibilities.

Father is the blueprint (class).

Children are the objects (instances).

Each child inherits from the father — but each child is different. Different personality. Different struggles. Different journey.

Father is defined once.

Then you can create multiple children — new child().

Same blueprint. Different instances.


The Coding Example: Error (Jo Tum Roz Use Karte Ho)

You've written this:

throw new Error("Something went wrong");

Error is a class (blueprint).

new Error() creates an object (instance).

Each error object is unique:

  • Different message

  • Different stack trace

  • Different time of creation

Same class. Different objects.


Father vs Error Class (Side by Side)

Father (Blueprint in Life) Error Class (Blueprint in Code)
Father has name, values, responsibilities Error has name, message, stack
Child is born using new Error object created using new Error()
Each child is unique Each error has different message, different stack
Children inherit father's qualities Error objects inherit .toString(), .message
Father doesn't change Class doesn't change

What is Object-Oriented Programming?

OOP is a way to write code where you model real-world things:

  • Error

  • User

  • Date

  • Request

Everything has properties (message, name) and methods (toString).

OOP lets you create a blueprint (class) and then create many objects from it.


What is a Class in JavaScript?

A class is a template. Ek blueprint.

class Error {
  // Class body
}

Class alone does nothing. You need to create objects from it.


Creating Objects Using Classes (The new Keyword)

const error1 = new Error("API failed");
const error2 = new Error("Database timeout");
const error3 = new Error("Invalid input");

console.log(error1.message); // "API failed"
console.log(error2.message); // "Database timeout"
console.log(error3.message); // "Invalid input"

new Error() → naya object banta hai. Har object apna message rakhta hai.


The Constructor Method

Constructor is a special method that runs automatically when an object is created.

Yahan tum properties set karte ho.

class CustomError {
  constructor(message, code) {
    this.message = message;
    this.code = code;
  }
}

const err = new CustomError("Something broke", 500);
console.log(err.message); // "Something broke"
console.log(err.code);    // 500

this refers to the current object.


Blueprint → Objects Diagram


Methods Inside a Class

Methods are functions inside a class that define an object's behavior.

class CustomError {
  constructor(message) {
    this.message = message;
  }

  // Method
  log() {
    console.log(`[ERROR] ${this.message}`);
  }

  toJSON() {
    return { error: this.message, timestamp: new Date() };
  }
}

const err = new CustomError("API failed");
err.log(); // [ERROR] API failed
console.log(err.toJSON()); // { error: "API failed", timestamp: "2026-..." }

Class → Instance Relationship


Why Every Developer Relates to This Example

You've felt this:

try {
  // something fails
  throw new Error("API failed");
} catch (err) {
  console.log(err.message); // "API failed"
  console.log(err.stack);   // where it happened
}

You create errors. You catch errors. You read their messages.

Har error object apni story batata hai. Kahan fail hua. Kyu fail hua.

That's OOP in action — without even realizing it.


Basic Idea of Encapsulation

Encapsulation means protecting data from direct access.

Error class's internal stack trace — you can't set it directly. JavaScript manages it internally.

class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    let _balance = balance; // Private

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

For beginners: encapsulation = hide internal details.


Why OOP? (Benefits)

Problem Without OOP With OOP
Multiple similar objects Copy-paste code One class, many objects
Different errors, same structure Object literal every time One Error class
Code organization Scattered Grouped in classes
Reusability Low High

Real-World Coding Examples (That Use new)

Example 1: Error (you use this daily)

const err = new Error("Failed");
console.log(err.stack);

Example 2: Date (you've used this)

const today = new Date();
console.log(today.toLocaleDateString());

Example 3: Promise (in async code)

const promise = new Promise((resolve, reject) => {
  // async task
});

Example 4: Custom Error (in real projects)

class ValidationError extends Error {
  constructor(field, message) {
    super(message);
    this.field = field;
  }
}

const err = new ValidationError("email", "Invalid format");

Important Note

JavaScript me classes ES6 (2015) me aayi. Pehle prototypes the.

Aur classes internally still prototypes use karti hain — but samajhne ke liye itna kaafi hai.

new keyword = object instantiation. Blueprint se real cheez banana.


Final Thought

OOP helps you write reusable, organized code. Ek baar class likho, sau objects banao. Har object unique. Yeh power hai. Yeh responsibility hai.