Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Published
9 min read

Introduction

Have you ever wondered how large applications manage thousands of pieces of data and make their code easy to maintain? The answer lies in Object-Oriented Programming, or OOP. In this blog, we will explore how OOP works in JavaScript and why it is so powerful.


1. What is Object-Oriented Programming (OOP)?

Object-Oriented Programming is a way of writing code where you organize your data and functions together based on real-world things. Instead of writing scattered functions and variables, OOP lets you group related information and actions into containers called objects.

Think of OOP as a way to model the real world inside your code. Just like in real life, everything around you can be thought of as an object - your phone, your car, your book, or even you yourself. Each of these has properties (what they are) and behaviors (what they can do).

In programming terms:

  • Properties are the data or attributes

  • Behaviors are the actions or methods


2. Real-World Analogy: Blueprint to Objects

Imagine you are a car manufacturer. You want to create multiple cars of the same model, like the Maruti Swift or Hyundai Creta.

How do you do this?

First, you create a blueprint (or design) of the car. This blueprint shows:

  • What color it can be

  • What engine it has

  • How many seats it has

  • What features it includes

Now, using this single blueprint, you can manufacture 100 cars, 1000 cars, or even more. Each car will have the same structure and features, but they can have different colors, registration numbers, or owners.

In programming:

  • The blueprint is called a class

  • Each manufactured car is called an object (or instance)

This is the core concept of OOP. You create a class once, and then you can create as many objects as you need from it.

JavaScript

// Blueprint (Class)
class Car {
  // Properties
  color = "red";
  model = "Swift";
  seats = 5;
}

// Objects created from the blueprint
const car1 = new Car();
const car2 = new Car();
const car3 = new Car();

3. What is a Class in JavaScript?

A class is a template or blueprint that defines the structure of an object. It tells JavaScript what properties and methods an object should have.

Think of a class as an instruction manual. When you follow the instructions, you create an actual object that can be used in your program.

Before classes, JavaScript used functions to create objects. But classes make the code cleaner and easier to understand, especially if you come from other programming languages like Python or Java.

Here is a simple class:

class Person {
  // This is where you define what properties and methods a Person should have
}

That is it! This is the basic structure. Now let us add more details to this class.


4. Creating Objects Using Classes

Now that you understand what a class is, let us learn how to create actual objects (called instances) from a class.

To create an object from a class, you use the new keyword:

class Car {
  // Class definition
}

// Creating objects from the class
const myCar = new Car();
const yourCar = new Car();

Here:

  • Car is the class (blueprint)

  • myCar and yourCar are objects (instances)

Each time you use new, JavaScript creates a fresh object based on the class blueprint.

Let me show you a more practical example:

class Student {
  // We will add details soon
}

// Creating objects
const student1 = new Student();
const student2 = new Student();
const student3 = new Student();

console.log(student1); // Student {}
console.log(student2); // Student {}

Right now, these student objects are empty. Let us add some properties to them.


5. Constructor Method

The constructor is a special method inside a class that runs automatically when you create a new object. It is used to set up the initial properties of the object.

Think of a constructor as the setup process when you buy a new phone. When you open the box and start the phone, it automatically sets things like language, time zone, and default settings. Similarly, a constructor sets up the initial values for your object.

Here is the syntax:

class Student {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}
  • constructor() is the special method that runs when you create a new object

  • this refers to the current object being created

  • this.name creates a property called name on the object

  • this.age creates a property called age on the object

Now when you create a student object, you can pass the student's name and age:

const student1 = new Student("Ashish", 20);
const student2 = new Student("Priya", 19);

console.log(student1.name);  // Output: Ashish
console.log(student1.age);   // Output: 20

console.log(student2.name);  // Output: Priya
console.log(student2.age);   // Output: 19

Perfect! Now each student object has its own name and age. This is much better than creating empty objects.


6. Methods Inside a Class

Methods are functions that belong to a class. They define the actions or behaviors that an object can perform.

For example, if you create a Bank Account class, it might have methods like:

  • Deposit money

  • Withdraw money

  • Check balance

Methods are written inside the class just like regular functions, but without the function keyword:

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

  // Method 1: Display student details
  displayDetails() {
    console.log(`Name: \({this.name}, Age: \){this.age}`);
  }

  // Method 2: Check if student is an adult
  isAdult() {
    return this.age >= 18;
  }
}

// Create a student object
const student = new Student("Ashish", 20);

// Call the methods
student.displayDetails();  // Output: Name: Ashish, Age: 20
console.log(student.isAdult());  // Output: true

Notice:

  • Methods are defined inside the class

  • You call methods using the object name followed by a dot and the method name

  • Inside methods, you use this to refer to the current object's properties

Let's understand with a another practical example with a car:

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

  showInfo() {
    console.log(`\({this.year} \){this.brand} ${this.model}`);
  }

  getAge() {
    const currentYear = 2026;
    return currentYear - this.year;
  }
}

const car1 = new Car("Maruti", "Swift", 2020);
const car2 = new Car("Hyundai", "Creta", 2018);

car1.showInfo();  // Output: 2020 Maruti Swift
console.log(car1.getAge());  // Output: 6

car2.showInfo();  // Output: 2018 Hyundai Creta
console.log(car2.getAge());  // Output: 8

This is the power of methods - they let your objects do things!


7. Basic Idea of Encapsulation

Encapsulation is the practice of bundling data (properties) and methods that work on that data together in one place (the class), and hiding unnecessary details from the outside world.

Think of it like your bank account. You do not need to know all the complicated database operations inside the bank. You just need to know how to deposit money, withdraw money, or check your balance. The bank encapsulates all the complex details and provides you with simple methods.

In JavaScript, we use a naming convention to indicate private properties. Properties that start with an underscore (_) are meant to be private, meaning they should not be accessed directly from outside:

class BankAccount {
  constructor(ownerName, initialBalance) {
    this.ownerName = ownerName;
    this._balance = initialBalance;  // Private property (hidden)
  }

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

  withdraw(amount) {
    if (amount > 0 && amount <= this._balance) {
      this._balance = this._balance - amount;
      console.log(`Withdrawn: \({amount}. New balance: \){this._balance}`);
    } else {
      console.log("Invalid withdrawal amount");
    }
  }

  getBalance() {
    return this._balance;
  }
}

const account = new BankAccount("Amit Patel", 5000);

account.deposit(2000);  // Output: Deposited: 2000. New balance: 7000
account.withdraw(1000);  // Output: Withdrawn: 1000. New balance: 6000
console.log(account.getBalance());  // Output: 6000

// You should not do this (it breaks encapsulation):
// account._balance = 10000;  // Don't do this!

Benefits of encapsulation:

  • Security: You cannot accidentally change important data

  • Control: Methods can validate the data before making changes

  • Maintainability: If the bank changes how it stores balance, only the class needs to change, not the code using it


Putting It All Together: Complete Example

Let me show you a complete Student class that brings together everything we learned:

class Student {
  constructor(name, age, rollNumber) {
    this.name = name;
    this.age = age;
    this.rollNumber = rollNumber;
    this._marks = 0;  // Private property
  }

  displayInfo() {
    console.log(`Name: ${this.name}`);
    console.log(`Age: ${this.age}`);
    console.log(`Roll Number: ${this.rollNumber}`);
  }

  addMarks(marks) {
    if (marks >= 0 && marks <= 100) {
      this._marks = marks;
      console.log(`Marks added: ${marks}`);
    } else {
      console.log("Invalid marks. Please enter between 0 and 100");
    }
  }

  getMarks() {
    return this._marks;
  }

  isPassed() {
    return this._marks >= 35;
  }

  printReport() {
    console.log("=== Student Report ===");
    this.displayInfo();
    console.log(`Marks: ${this.getMarks()}`);
    console.log(`Status: ${this.isPassed() ? "Passed" : "Failed"}`);
    console.log("=======================");
  }
}

const student1 = new Student("Raj Kumar", 18, 101);
const student2 = new Student("Priya Sharma", 17, 102);
const student3 = new Student("Aman Singh", 18, 103);

student1.addMarks(78);
student1.printReport();
// Output:
// === Student Report ===
// Name: Raj Kumar
// Age: 18
// Roll Number: 101
// Marks: 78
// Status: Passed
// =======================

student2.addMarks(32);
student2.printReport();
// Output:
// === Student Report ===
// Name: Priya Sharma
// Age: 17
// Roll Number: 102
// Marks: 32
// Status: Failed
// =======================

Key Takeaways

  1. OOP is about organizing code using real-world concepts

  2. Class is a blueprint that defines the structure of objects

  3. Objects are instances created from a class using the new keyword

  4. Constructor is a special method that sets up initial properties

  5. Methods are functions that belong to a class and define behaviors

  6. Encapsulation means hiding internal details and providing controlled access through methods

  7. Classes make code reusable, organized, and easy to maintain


Summary

  1. OOP is a way to organize code using classes and objects

  2. Class is a blueprint that defines properties and methods

  3. Object (or instance) is created from a class using the new keyword

  4. Constructor is a special method that runs when creating an object

  5. Methods are functions that belong to a class and define what objects can do

  6. this refers to the current object

  7. Encapsulation means bundling data and functions together

  8. Properties store data about an object

  9. Methods define actions that objects can perform

  10. Reusability is a key benefit of OOP - create many objects from one class