Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Updated
6 min readView as Markdown
Understanding Object-Oriented Programming in JavaScript

Introduction

If you have been writing JavaScript for a while, you have probably written functions, worked with arrays, and maybe even built small projects. But as your code grows bigger, things can get messy and hard to manage.

That is where Object-Oriented Programming (OOP) comes in. It helps you write code that is clean, organized, and easy to reuse.

In this article, we will break down OOP in JavaScript in the simplest way possible — no confusing jargon, just clear explanations and practical examples.


1. What is Object-Oriented Programming?

Object-Oriented Programming (OOP) is a way of writing code by organizing it into objects.

Instead of writing a bunch of separate variables and functions, you group related data and behavior together into one unit called an object.

Think of it this way:

Instead of having a carName, carColor, and startCar() floating around separately — you bring them all together inside one car object.

This makes your code easier to read, easier to maintain, and easier to reuse.


2. The Real-World Analogy — Blueprint and Objects

Let's use a simple real-world example to understand this.

Imagine you are an architect and you design a blueprint for a house. The blueprint defines:

  • How many rooms the house has

  • What color the walls are

  • How the doors open

Now, using that one blueprint, you can build many different houses. Each house is its own separate building, but they all follow the same plan.

In programming:

Real World JavaScript
Blueprint Class
House built from blueprint Object (Instance)
Features of the house Properties
Things the house can do Methods

This is the core idea of OOP. A class is the blueprint, and objects are what you create from it.


3. What is a Class in JavaScript?

A class is a template or blueprint used to create objects.

It was introduced in ES6 (2015) and made it much easier to write OOP in JavaScript.

Here is the basic syntax:

class ClassName {
  constructor() {
    // properties go here
  }

  methodName() {
    // behavior goes here
  }
}

Simple, right? Let's now bring this to life with a real example.


4. Creating Objects Using Classes

Let's create a Car class and then build car objects from it.

class Car {
  constructor(brand, color) {
    this.brand = brand;
    this.color = color;
  }

  describe() {
    console.log(`This is a \({this.color} \){this.brand}.`);
  }
}

// Creating objects from the Car class
const car1 = new Car("Toyota", "red");
const car2 = new Car("Honda", "blue");

car1.describe(); // This is a red Toyota.
car2.describe(); // This is a blue Honda.

Here, car1 and car2 are two separate objects created from the same class. They share the same structure but have different data.

This is the power of classes — write once, use many times.


5. The Constructor Method

The constructor() is a special method inside a class. It runs automatically when you create a new object using new.

Its job is to set up the initial properties of the object.

class Person {
  constructor(name, age) {
    this.name = name; // 'this' refers to the current object
    this.age = age;
  }
}

const person1 = new Person("Alice", 25);
console.log(person1.name); // Alice
console.log(person1.age);  // 25

💡 Note: this refers to the specific object being created. So when you write this.name, you are saying "this particular object's name".


6. Methods Inside a Class

A method is simply a function that belongs to a class. Methods define what an object can do.

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

  greet() {
    console.log(`Hi, I am \({this.name} and I am in grade \){this.grade}.`);
  }

  study() {
    console.log(`${this.name} is studying hard!`);
  }
}

const student1 = new Student("Ravi", 10);
student1.greet();  // Hi, I am Ravi and I am in grade 10.
student1.study();  // Ravi is studying hard!

You can add as many methods as you need inside a class. Each method describes a specific action or behavior.


7. Basic Idea of Encapsulation

Encapsulation means keeping the data (properties) and the behavior (methods) of an object bundled together in one place.

It also means hiding the internal details and only exposing what is necessary.

Here is a simple analogy:

Think of a TV remote. You press a button and the channel changes. You do not need to know the electronics inside. The complexity is hidden. You only interact with what is exposed — the buttons.

In code, this looks like:

class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    this._balance = balance; // The underscore suggests it's private by convention
  }

  deposit(amount) {
    this._balance += amount;
    console.log(`Deposited ₹\({amount}. New balance: ₹\){this._balance}`);
  }

  getBalance() {
    return this._balance;
  }
}

const account = new BankAccount("Priya", 5000);
account.deposit(1000); // Deposited ₹1000. New balance: ₹6000
console.log(account.getBalance()); // 6000

The balance is not changed directly from outside. It is managed through methods, which is the basic spirit of encapsulation.


Assignment — Try It Yourself!

Now it is your turn. Here is a small assignment to test what you have learned:

Task: Create a Student class with the following:

  1. Properties: name and age

  2. A method called printDetails() that prints the student's name and age

  3. Create at least 3 student objects and call printDetails() on each

Starter Code:

class Student {
  constructor(name, age) {
    // your code here
  }

  printDetails() {
    // your code here
  }
}

// Create student objects below
const s1 = new Student("Aman", 18);
const s2 = new Student("Sneha", 19);
const s3 = new Student("Rahul", 20);

s1.printDetails();
s2.printDetails();
s3.printDetails();

Expected Output:

Name: Aman, Age: 18
Name: Sneha, Age: 19
Name: Rahul, Age: 20

Give it a try before looking at the solution!


Quick Recap

Concept What It Means
OOP A way to organize code using objects
Class A blueprint to create objects
Object An instance created from a class
Constructor A method that sets up an object when created
Method A function that belongs to a class
Encapsulation Bundling data and behavior together

Final Thoughts

Object-Oriented Programming might sound complex at first, but once you understand the analogy of blueprints and objects, everything starts to click.

Here is what to remember:

  • A class is just a template

  • An object is a real thing created from that template

  • The constructor sets up the object

  • Methods define what the object can do

  • Encapsulation keeps things organized and protected

Start small. Create a Person class. Then a Car class. Then a Student class. Practice is the fastest way to make this feel natural.

Happy coding!