Skip to main content

Command Palette

Search for a command to run...

OOP in JavaScript

Understanding Object-Oriented Programming in JavaScript

Published
4 min read
OOP in JavaScript

Object-Oriented Programming (OOP) is a programming paradigm that organizes software design around data, or objects, rather than functions and logic. Think of it as a way to model real-world things in your code.

Why ?

Imagine you are a car manufacturer. You don’t just start building a car from scratch every time. Instead, you create a blueprint. This blueprint defines the features (color, engine) and actions (drive, brake).

  • The Blueprint is the Class.

  • The Physical Car on the road is the Object (or Instance).

What is a Class in JavaScript?

Introduced in ES6, a class is a template for creating objects. It encapsulates data (properties) and behavior (methods) into a single unit, promoting code reusability.

Let’s look at how to translate that blueprint into JavaScript code.

class Car {
  // The Constructor: The "Setup" function
  constructor(brand, model, color) {
    this.brand = brand;
    this.model = model;
    this.color = color;
  }

  // A Method: Defining behavior
  drive() {
    console.log(`The \({this.color} \){this.brand} is now driving!`);
  }
}

// Instantiating Objects (Creating cars from the blueprint)
const myCar = new Car("Tesla", "Model 3", "White");
const friendsCar = new Car("Tata", "Nexon", "Blue");

myCar.drive(); // Output: The White Tesla is now driving!

Breakdown

  • The Constructor Method: This is a special method that runs automatically when you create a new object. It’s where you initialize the object's properties using the this keyword.

  • Methods: These are functions defined inside the class that describe what the object can do.

  • Encapsulation (The Basics): This is the practice of "bundling" the data and the methods that operate on that data within one unit (the class). It keeps the code organized and prevents outside code from accidentally messing with the internal logic.

Example - The Student Class

class Student {
  constructor(name, age, course) {
    this.name = name;
    this.age = age;
    this.course = course;
  }

  // Method to display details
  displayDetails() {
    console.log(`Student: \({this.name}, Age: \){this.age}, Course: ${this.course}`);
  }
}

// Creating multiple student objects
const student1 = new Student("Satpal", 24, "Full Stack Development");
const student2 = new Student("Aman", 22, "Data Science");

student1.displayDetails();
student2.displayDetails();

The Four Pillars of OOP

Encapsulation (Data Hiding)

Encapsulation is about keeping the internal state of an object private and only exposing what is necessary through a public interface. In modern JavaScript (ES2022+), we use the # prefix for truly private fields.

class BankAccount {
  #balance = 0; // Private field

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

  getBalance() {
    return `Your balance is ₹${this.#balance}`;
  }
}

const myAcc = new BankAccount();
myAcc.deposit(500);
console.log(myAcc.#balance); // Error: Private field '#balance' must be declared in an enclosing class

Abstraction (Complexity Hiding)

Abstraction means showing only the essential features of an object and hiding the "how it works" logic. You may know how to use a fetch() call in your Angular app/ React App, but you don't need to know the low-level TCP/IP handshake logic happening in the background.

Inheritance (Hierarchy)

Inheritance allows one class to derive properties and methods from another. In JS, we use extends and super().

class User {
  constructor(username) {
    this.username = username;
  }
  logIn() { console.log(`${this.username} logged in.`); }
}

class Admin extends User {
  deleteUser(user) { console.log(`Admin deleted ${user}`); }
}

Polymorphism (Many Forms)

Polymorphism allows different classes to be treated as instances of the same parent class through the same interface, but each responds in its own way.

class Shape {
  draw() { console.log("Drawing a shape..."); }
}

class Circle extends Shape {
  draw() { console.log("Drawing a circle ⭕"); } // Overriding
}

Prototypal Inheritance:

Unlike Classical OOP (C++/Java), JavaScript uses Prototypal Inheritance. Every object in JS has a hidden property called [[Prototype]] (accessible via __proto__).

  • When you call a method on an object, JS first looks at the object itself.

  • If it doesn't find it, it looks at the object's Prototype.

  • It keeps going up the "Prototype Chain" until it reaches null.

By using Classes and the Four Pillars (Encapsulation, Abstraction, Inheritance, and Polymorphism), you ensure that your code is:

  1. Maintainable: Changes in one class don't break the whole app.

  2. Scalable: Adding new features becomes a matter of extending existing logic.

  3. Readable: Your code tells a story about real-world objects.

Let's Connect! 🚀

I’m currently deep-diving into the JavaScript, building projects and exploring the internals of the web. If you're on a similar journey or just love talking about JavaScript, let’s stay in touch!

Keep coding and keep building.

JavaScript

Part 16 of 24

Master JavaScript from the ground up with a structured, easy-to-follow learning path designed for serious developers. This series starts with core fundamentals like variables, data types, and control flow, then gradually moves into deeper topics such as functions, scope, prototypes, asynchronous programming, and how the JavaScript engine works internally. Each lesson focuses on clarity and real understanding. You will learn not only how to write JavaScript, but why it behaves the way it does. Concepts are explained using simple examples, practical use cases, and clean coding patterns that reflect real-world development.

Up next

Understanding Objects in JavaScript

Beginner guide to understand what objects are in JavaScript