Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Object Oriented Programming in JavaScript

Updated
8 min read
Understanding Object-Oriented Programming in JavaScript

Object-Oriented Programming (OOP) is a way of organizing code that models real-world things as objects. Each object contains data (properties) and functions (methods) that describe its behavior.

1) What Object-Oriented Programming (OOP) means

Object‑Oriented Programming (OOP) is a programming paradigm (a style of writing programs) that focuses on modeling a system as a collection of objects. Each object represents a part of the system and contains both data and the functions that operate on that data.

  • An object is a self-contained entity that bundles:

    1. Attributes (data/properties) – describe the object

    2. Methods (functions/behaviors) – define what the object can do

  • A class is like a blueprint for creating objects. Each object created from the class is called an instance.

Simple Analogy

Concept Programming Example
Blueprint class Car: defines what a car has and can do
Actual Car my_car = Car("Red", "Toyota") is a real car created from that blueprint
Properties color, brand
Methods drive(), stop()
class Car:
    def __init__(self, brand, color):
        self.brand = brand
        self.color = color

    def drive(self):
        print(f"{self.brand} is driving!")

my_car = Car("Toyota", "Red")
my_car.drive()


Output:
Toyota is driving!

2) Real-world analogy (blueprint → objects)

Analogy: Car Blueprint → Car Objects

  • Blueprint = Class → defines what a car has (brand, color) and can do (drive, stop)

  • Actual car = Object (Instance) → a real car built from the blueprint

Explanation:

  1. Car → blueprint describing a car’s properties and behaviors

  2. car1 and car2 → actual cars created from the blueprint

  3. brand & color → attributes (data)

  4. drive() → behavior (method)

// Class (Blueprint)
class Car {
  constructor(brand, color) {
    this.brand = brand;  // property
    this.color = color;  // property
  }

  drive() {              // method
    console.log(`${this.brand} is driving!`);
  }
}

// Creating objects (instances)
const car1 = new Car("Toyota", "Red");
const car2 = new Car("Honda", "Blue");

car1.drive(); // Output: Toyota is driving!
car2.drive(); // Output: Honda is driving!

3) What is a class in JavaScript

What is a Class in JavaScript?

A class is a blueprint for creating objects. It defines:

  1. Properties – the data or characteristics that objects will have

  2. Methods – the behaviors or actions that objects can perform

You can create many objects (instances) from the same class, each with its own values but sharing the same structure and behavior.

Example

  • class Student → defines the blueprint for students

  • constructor() → sets up the object’s initial properties

  • this → refers to the object being created

  • student1 and student2 → actual student objects created from the class

// Define a class (blueprint)
class Student {
  constructor(name, grade) {
    this.name = name;   // property
    this.grade = grade; // property
  }

  study() {             // method
    console.log(`${this.name} is studying.`);
  }
}

// Create objects (instances)
const student1 = new Student("Alice", "A");
const student2 = new Student("Bob", "B");

student1.study(); // Alice is studying.
student2.study(); // Bob is studying.

4) Creating objects using classes

A class is a blueprint, and an object is an actual instance created from that blueprint. You use the new keyword to create objects.

Step 1: Define a Class

  • class Car → defines the blueprint

  • constructor() → sets up initial properties for each object

  • this → refers to the object being created

  • drive() → defines behavior of the object

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

  drive() {              // method
    console.log(`${this.brand} is driving!`);
  }
}

Step 2: Create Objects (Instances)

  • car1 and car2 are different objects created from the same class.

  • Each object has its own properties, but they share the same methods from the class.

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

car1.drive(); // Output: Toyota is driving!
car2.drive(); // Output: Honda is driving!

Step 3: Access Properties and Methods

  • You can access each object’s properties individually.

  • Methods are shared but operate on the object that calls them.

console.log(car1.color); // Red
console.log(car2.brand); // Honda

5) Constructor method

A constructor is a special method inside a class that runs automatically when you create a new object.

  • It is used to initialize the object’s properties.

  • Every class can have one constructor.

  • You define it using the keyword constructor() inside the class.

Example: Using a Constructor

  • constructor(name, grade) → runs automatically when new Student(...) is called

  • this.name and this.grade → assign values to the object’s properties

  • The objects student1 and student2 are initialized with their own data

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

  study() {                    // regular method
    console.log(`${this.name} is studying.`);
  }
}

// Creating objects
const student1 = new Student("Sudhanshu", "A");
const student2 = new Student("Sham", "B");

console.log(student1.name);  // Sudhanshu
console.log(student2.grade); // B

student1.study(); // Alice is studying.
student2.study(); // Sham is studying.

6) Methods inside a class

A method is a function defined inside a class that describes the behavior or actions of the objects created from that class.

  • Methods are shared by all objects of the class.

  • They can access the object’s properties using this.

Example: Methods in a Class

  • drive() and stop() are methods that describe what a Car object can do.

  • this.brand refers to the brand of the specific object calling the method.

  • All objects of the class share the same methods but operate on their own data.

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

  drive() {               // method
    console.log(`${this.brand} is driving.`);
  }

  stop() {                // another method
    console.log(`${this.brand} has stopped.`);
  }
}

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

// Call methods
car1.drive(); // Toyota is driving.
car1.stop();  // Toyota has stopped.
car2.drive(); // Honda is driving.
car2.stop();  // Honda has stopped.

7) Basic idea of encapsulation

Encapsulation is the concept of keeping an object’s data (properties) and methods together while restricting direct access to some of the object’s internal details.

  • It helps protect data from being changed unexpectedly.

  • Objects provide controlled ways to access or modify data through methods.

Think of it like a capsule or box: the important data is inside, and you interact with it only through the functions provided.

Example

  • _balance → marked with an underscore to show it’s intended as private (convention in JS).

  • getBalance() and deposit() → methods control access to _balance.

  • This prevents external code from changing the balance directly, which could cause errors.

class BankAccount {
  constructor(owner, balance) {
    this.owner = owner;
    this._balance = balance; // "private" property by convention
  }

  // Method to view balance
  getBalance() {
    return this._balance;
  }

  // Method to deposit money
  deposit(amount) {
    if (amount > 0) {
      this._balance += amount;
      console.log(`\({amount} deposited. New balance: \){this._balance}`);
    } else {
      console.log("Invalid deposit amount.");
    }
  }
}

const account = new BankAccount("Alice", 1000);

console.log(account.getBalance()); // 1000
account.deposit(500);              // 500 deposited. New balance: 1500

Assignment: Create a Student Class

Objective:

Practice creating a class, adding properties, defining a method, and creating multiple objects from the class.

Step 1: Create the Class

class Student {
  constructor(name, age) {      // constructor to initialize properties
    this.name = name;
    this.age = age;
  }

  showDetails() {               // method to print student details
    console.log(`Name: \({this.name}, Age: \){this.age}`);
  }
}

Step 2: Create Multiple Student Objects

const student1 = new Student("Sudhanshu", 20);
const student2 = new Student("Anita", 22);
const student3 = new Student("Rahul", 21);

Step 3: Call the Method for Each Student

student1.showDetails();  // Name: Sudhanshu, Age: 20
student2.showDetails();  // Name: Anita, Age: 22
student3.showDetails();  // Name: Rahul, Age: 21

Expected Output

Name: Sudhanshu, Age: 20
Name: Anita, Age: 22
Name: Rahul, Age: 21

summary

Object-Oriented Programming (OOP) models a system using objects that combine data (attributes) and functions (methods). A class is a blueprint for creating objects with shared behavior but individual data. Encapsulation bundles an object’s data and methods, controlling access to protect the data. In JavaScript, classes use a constructor to initialize properties, and objects are created with the new keyword, allowing code reuse and organized structure.