Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming (OOP) in JavaScript

Updated
10 min read
Understanding Object-Oriented Programming (OOP) in JavaScript
C

CSE student documenting my learning in databases, networking, and web fundamentals.

In the previous article, we explored Objects in JavaScript and learned how objects allow us to store structured data using key-value pairs.
We saw how Objects are extremely useful when we want to represent real-world entities such as users, students, or products.

However, as applications grow larger, we often need to create many objects with a similar structure.

For example, imagine we are building a system to manage students in a college.

We might need objects like:

const student1 = {
  name: "Rahul",
  age: 20
};

const student2 = {
  name: "Amit",
  age: 21
};

As you can see, both objects have the same structure, but we are repeating the same code again and again, which leads to code duplication.

So the natural question becomes:

Is there a way to create multiple objects with the same structure without repeating code every time?

This is where Object-Oriented Programming (OOP) comes in.


In this article, we will explore:

  • What Object-Oriented Programming (OOP) means

  • The concept of classes in JavaScript

  • How to create objects using classes

  • The constructor method

  • How to define methods inside a class

  • The basic idea of encapsulation

By the end of this article, you will understand how OOP helps us write more organized, reusable, and scalable JavaScript code.

Let’s start by understanding what Object-Oriented Programming actually means.


What is Object-Oriented Programming (OOP)?

Object-Oriented Programming (OOP) is a programming approach that helps us organize our code around objects.

Instead of only focusing on functions and data separately, OOP combines data and behavior together inside objects.

For example, consider a car.

A car has certain properties, such as:

  • brand

  • color

  • speed

And it can perform certain actions such as:

  • start

  • accelerate

  • brake

Similarly, in Object-Oriented Programming, we represent this idea in code by creating objects that contain both:

  • data (properties)

  • behavior (methods)


Real World Analogy

To understand OOP better, let’s look at a simple real-world analogy.

When engineers manufacture cars, they do not design each car from scratch. Instead, they create a blueprint that defines the structure of the car.

The blueprint describes things like:

  • engine type

  • number of wheels

  • car model

Once the blueprint is ready, many cars can be created from it.

Similarly, in Object-Oriented Programming:

  • The blueprint is called a class

  • The cars created from that blueprint are called objects (instances)

For example:

This approach allows us to reuse code and create multiple objects with the same structure without rewriting everything.

Let’s explore what a class is in JavaScript in the next section.


What is a Class in JavaScript?

In the previous section, we saw that Object-Oriented Programming uses the idea of a blueprint to create multiple objects with the same structure.

In JavaScript, this blueprint is called a class.

A class is a template used to create objects with predefined properties and methods.

Instead of manually creating many objects with the same structure, we can define a class once and then create multiple objects from it.

Syntax

A basic class in JavaScript looks like this:

class ClassName {
  // properties and methods
}

Here:

  • class is the keyword used to define a class

  • ClassName is the name of the class

By convention, class names usually start with a capital letter.

Example:

Let's create a simple class called Car.

class Car {
}

Right now, this class is empty. But it will act as a blueprint for creating car objects.

Later, we can add properties and methods inside this class.


Why Classes Are Useful

Imagine we want to create multiple car objects. Without classes, we might write something like this:

const car1 = {
  brand: "Toyota",
  color: "Red"
};

const car2 = {
  brand: "Honda",
  color: "Blue"
};

Here we are repeating the same structure for every object.

So using a class allows us to define this structure once and reuse it. This makes our code:

  • easier to organize

  • easier to reuse

  • easier to maintain

Now that we understand what a class is, the next step is learning how to create objects using a class.


Creating Objects Using Classes

Objects created from a class are called instances.

To create an object from a class in JavaScript, we use the new keyword.

Syntax

const objectName = new ClassName();

Here:

  • new tells JavaScript to create a new object

  • ClassName is the class we defined earlier

  • objectName is the variable that stores the created object

Example:

Let's use the Car class we created earlier.

class Car {

}

const car1 = new Car();
const car2 = new Car();

In this example:

  • car1 and car2 are objects created from the Car class

  • Both objects follow the structure defined by the class


Visual Representation

We can visualize this like this:

The class acts as a blueprint, and each object created from it becomes an instance of that class.


However, right now our Car class is empty. That means the objects we create do not contain any properties yet.

To define properties when objects are created, JavaScript provides a special method called the constructor.

Let’s explore the constructor method in the next section.


The Constructor Method

The constructor is a special method inside a class that runs automatically when a new object is created.

It is commonly used to assign initial values to object properties.

Syntax

class ClassName {
  constructor(parameters) {
    // initialize properties
  }
}

Here:

  • constructor() is the special method

  • parameters are values passed when creating the object

  • inside the constructor we assign those values to the object's properties

Example:

Let’s update our Car class to include a constructor.

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

Here:

  • brand and color are parameters passed to the constructor

  • this.brand and this.color store those values inside the object

Don't worry if this seems confusing right now. We'll learn this in detail in our next article.


Creating Objects

Now we can create car objects with specific values.

const car1 = new Car("Toyota", "Red");
const car2 = new Car("Honda", "Blue");

console.log(car1);
console.log(car2);

Output:

Car { brand: "Toyota", color: "Red" }
Car { brand: "Honda", color: "Blue" }

What Happened Here?

When we wrote:

const car1 = new Car("Toyota", "Red");

JavaScript automatically called the constructor and executed:

this.brand = "Toyota"
this.color = "Red"

So the object car1 now contains:

{
  brand: "Toyota",
  color: "Red"
}

The same process happens when creating car2.


Visual Representation

The constructor ensures that every object created from the class starts with the required properties.


So far, we have learned how to use a constructor to assign properties when creating objects. However, objects do not just store data. They can also perform actions.

In Object-Oriented Programming, these actions are defined using methods. Let's see how.


Methods Inside a Class

A method is simply a function defined inside a class.

Methods allow objects to perform certain operations using the data they contain.

Syntax

Methods are defined inside a class like this:

class ClassName {
  constructor(parameters) {
    // initialize properties
  }

  methodName() {
    // code to execute
  }
}

Here:

  • methodName() is the method defined inside the class

  • the method can access the object's properties using the this keyword

Example:

Let’s extend our Car class by adding a method that prints the car's details.

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

  displayInfo() {
    console.log("Brand:", this.brand);
    console.log("Color:", this.color);
  }
}

Here we added a method called displayInfo(). This method prints the car's brand and color.


Creating Objects and Calling the Method

const car1 = new Car("Toyota", "Red");
const car2 = new Car("Honda", "Blue");

car1.displayInfo();
car2.displayInfo();

Output:

Brand: Toyota
Color: Red
Brand: Honda
Color: Blue

What Happened Here?

When we called:

car1.displayInfo();

JavaScript executed the displayInfo() method and used:

this.brand
this.color

to access the properties of car1.

Similarly, when we called:

car2.displayInfo();

the method used the values stored inside the car2 object.


Key Idea

Each object created from the class:

  • has its own data (properties)

  • can use the same methods defined in the class

This is one of the key advantages of Object-Oriented Programming because it allows us to reuse code efficiently.


Now that we understand how classes define properties and methods, the next step is to briefly explore the concept of encapsulation.


Basic Idea of Encapsulation

One of the important ideas in Object-Oriented Programming is encapsulation.

In simple terms, encapsulation means bundling related data and behavior together inside a single unit.

Instead of keeping data and functions separate, OOP allows us to combine them in one place.

Example:

Let's look at our Car class again.

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

  displayInfo() {
    console.log("Brand:", this.brand);
    console.log("Color:", this.color);
  }
}

Here the class contains:

  • properties (data)brand, color

  • method (behaviour)displayInfo()

Both the data and the behavior related to a car are grouped together inside the class. This is the idea behind encapsulation.


Why Encapsulation is Useful

Encapsulation helps make our code:

  • more organized

  • easier to understand

  • easier to maintain

Instead of spreading related logic across different parts of the program, we keep everything inside a single class.


Practice Time

Now that we have explored the basics of Object-Oriented Programming in JavaScript, let’s practice a small example to reinforce what we’ve learned.

1. Create a Student Class

Create a class called Student that stores information about a student and a method that displays the information.

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

  displayDetails() {
    console.log("Name:", this.name);
    console.log("Age:", this.age);
  }
}

2. Create Multiple Student Objects

Now create a few objects from this class.

const student1 = new Student("Rahul", 20);
const student2 = new Student("Amit", 21);
const student3 = new Student("Neha", 19);

3. Call the Method

Use the method to print the student details.

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

Try modifying the values or adding new methods to see how classes and objects behave.

Practicing small examples like this will help you understand how OOP works in JavaScript.


Wrapping Up

In this article, we explored the basics of Object-Oriented Programming (OOP) in JavaScript.

We learned:

  • What Object-Oriented Programming means

  • How classes act as blueprints for objects

  • How to create objects using classes

  • How the constructor initializes object properties

  • How to define methods inside a class

  • The basic idea of encapsulation

OOP helps us write code that is more organized, reusable, and easier to maintain, especially in larger applications.


What's Next?

So far in this series, we have explored several JavaScript Topics.

In the next article, we will explore the this keyword in JavaScript and understand how it behaves in different contexts.

This concept is important because it plays a key role when working with objects and classes.


⬅ Previous Article: Objects in JavaScript

➡ Next Article: this, call(), bind() and apply() in JavaScript

JavaScript Foundations

Part 2 of 11

This series documents my journey of learning JavaScript from the ground up. Each article explains core JavaScript concepts in a beginner-friendly way with simple examples and practical explanations. Topics include variables, operators, control flow, functions, arrow functions, arrays, objects, and more. If you're starting your JavaScript journey, this series will help you build a strong foundation step by step.

Up next

Understanding Objects in JavaScript: A Beginner-Friendly Guide

In the previous articles, we explored Arrays and Array Methods in JavaScript and learned how methods like map(), filter(), and reduce() help us work with arrays more efficiently. We saw that arrays ar