Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Updated
11 min read
Understanding Object-Oriented Programming in JavaScript

Introduction:

OOP is a programming paradigm where you model your code using “objects” that represent real-world things. Each object can have:

  • Properties (Attributes) – these describe the object (like name, age).

  • Methods (Behaviors/Functions) – actions the object can perform (like walk(), greet()).

In simple words:

Objects = Nouns, Methods = Verbs

How JavaScript Does OOP

a) Using Objects (Object Literals)

You can create objects directly:

const person = {
  name: "Mohit",
  age: 25,
  greet: function() {
    console.log(`Hello, my name is ${this.name}`);
  }
};

person.greet(); 

Output:

Hello, my name is Mohit

=== Code Execution Successful ===

Here:

  • name and age are properties.

  • greet() is a method.

  • this refers to the object itself (person).

b) Using Constructor Functions

Before ES6, this was the main way to create “object blueprints”:

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log(`Hi, I'm ${this.name}`);
  };
}

const person1 = new Person("Mohit", 25);
const person2 = new Person("Payal", 23);

person1.greet(); 
person2.greet(); 

Output:

Hi, I'm Mohit
Hi, I'm Payal

=== Code Execution Successful ===
  • new creates a new object based on the constructor function.

  • Each object has its own copy of methods (less efficient if many objects are created).

c) Using ES6 Classes (Modern Way)

Classes are syntactic sugar over constructor functions:

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

  greet() {
    console.log(`Hi, I'm ${this.name}`);
  }
}

const person1 = new Person("Mohit", 25);
person1.greet(); 

Output:

Hi, I'm Mohit

=== Code Execution Successful ===

Advantages:

  • Cleaner syntax.

  • Supports inheritance easily.

  • Methods are stored on the prototype, saving memory.

d) Inheritance (Sharing Features)

OOP is powerful because objects can inherit properties and methods:

class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    console.log(`${this.name} makes a sound`);
  }
}

class Dog extends Animal {
  speak() {
    console.log(`${this.name} barks`);
  }
}

const dog = new Dog("Buddy");
dog.speak(); 

Output:

Buddy barks

=== Code Execution Successful ===
  • extends lets Dog inherit from Animal.

  • super() calls the parent constructor.

Key OOP Concepts in JS

  1. Encapsulation – Keep related data and methods together.

  2. Abstraction – Only expose what’s necessary (private properties/methods).

  3. Inheritance – Share methods and properties between classes.

  4. Polymorphism – Same method name can behave differently (like speak() above).

1. Blueprint to Objects

  • Class = Blueprint

  • Object = House built from the blueprint

Imagine you’re building houses:

class House {
  constructor(color, rooms) {
    this.color = color;
    this.rooms = rooms;
  }
  describe() {
    console.log(`This house is \({this.color} with \){this.rooms} rooms.`);
  }
}
  • The House class is like an architectural plan.

  • It doesn’t exist physically yet.

  • describe() is a behavior every house made from this plan can do.

Now we build some houses (objects) from this blueprint:

const house1 = new House("blue", 3);
const house2 = new House("red", 5);

house1.describe(); 
house2.describe(); 
  • house1 and house2 are individual houses, each with its own color and number of rooms.

  • Both share the same blueprint (class), so they have the same structure and methods.

2. Inheritance Analogy

  • Suppose you want a special type of house: Mansion.

  • It’s like extending the blueprint of a regular house:

class Mansion extends House {
  constructor(color, rooms, pool) {
    super(color, rooms); 
    this.pool = pool;
  }
  describe() {
    console.log(`This mansion is \({this.color} with \){this.rooms} rooms and a ${this.pool ? "pool" : "no pool"}.`);
  }
}

const mansion1 = new Mansion("white", 10, true);
mansion1.describe(); 
  • Mansion inherits properties from House, but also has something extra (pool).

  • This is like real-world specialization.

3. TL;DR Analogy

OOP Concept Real-world Analogy
Class Blueprint / Plan for a house
Object Actual house built from the blueprint
Property Color, rooms, pool of the house
Method Actions house can “do” (e.g., describe itself)
Inheritance Mansion blueprint extends House blueprint

Class in Javascript:

A class in JavaScript is essentially a blueprint for creating objects. It defines what properties (data) and methods (functions/behaviors) the objects created from it will have.

Think of it as a recipe or plan: it doesn’t make anything by itself, but you can use it to make multiple objects that follow the same design.

Syntax of a Class:

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

  greet() {                  
    console.log(`Hi, I'm ${this.name}`);
  }
}

const person1 = new Person("Mohit", 25);
const person2 = new Person("Palak", 23);

person1.greet(); 
person2.greet(); 

Output:

Hi, I'm Mohit
Hi, I'm Palak

=== Code Execution Successful ===

Breakdown:

  • class Person { ... } : defines the blueprint

  • constructor(name, age) : special method that runs when a new object is created

  • this.name and this.age : properties of the object

  • greet() : method shared by all instances

  • new Person(...) : creates an actual object from the blueprint

Creating objects using classes:

1. Define a Class: First, you need a blueprint a class:

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

  greet() {  
    console.log(`Hi, I'm \({this.name} and I'm \){this.age} years old`);
  }
}
  • constructor : initializes object properties when it’s created.

  • greet() : a method all objects from this class can use.

2. Create Objects (Instances): Use the new keyword to create objects from a class:

const person1 = new Person("Mohit", 25);
const person2 = new Person("Palak", 23);
  • person1 and person2 are separate objects.

  • Each has its own properties (name and age) but shares the same methods (greet).

3. Access Properties and Methods:

console.log(person1.name); 
console.log(person2.age);  

person1.greet(); 
person2.greet(); 

4. Real-world Analogy:

  • Class : blueprint of a car

  • Object : actual car you buy from the factory

  • Each car can have different color, model, etc., but they all can drive, honk, and stop

5. Optional: Multiple Objects at Once

const people = [
  new Person("Amit", 30),
  new Person("Neha", 28),
  new Person("Rohan", 35)
];

people.forEach(p => p.greet());

Output:

Hi, I'm Amit and I'm 30 years old
Hi, I'm Neha and I'm 28 years old
Hi, I'm Rohan and I'm 35 years old

All objects share the same blueprint, but each one has its own unique data.

Constructor method:

1. What is a Constructor?

  • The constructor is a special method inside a class.

  • It runs automatically when you create a new object using new.

  • Its job: initialize the object’s properties.

Think of it like setting up a new toy: you tell it the color, size, and name when you first get it-constructor does that for your object.

2. Syntax:

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

  greet() {
    console.log(`Hi, I'm ${this.name}`);
  }
}
  • constructor(name, age) : takes arguments to initialize the object.

  • this.name and this.age : this refers to the object being created.

3. Creating Objects with Constructor:

const person1 = new Person("Mohit", 25);
const person2 = new Person("Palak", 23);

console.log(person1.name); 
console.log(person2.age);  

person1.greet(); 
person2.greet(); 
  • new Person("Mohit", 25) automatically calls the constructor and sets properties.

  • You don’t call the constructor manually; new handles it.

4. Important Points About Constructor:

  1. A class can only have one constructor.

  2. If you don’t define a constructor, JavaScript creates an empty one automatically.

  3. this inside the constructor always refers to the object being created.

  4. You can pass any number of arguments to the constructor.

5. Real-world Analogy:

  • Class : blueprint for a car

  • Constructor : when a car is built, constructor decides the color, model, and engine type

  • Object : actual car built with those choices

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

const car1 = new Car("Toyota", "Red");
console.log(car1.brand); 
console.log(car1.color); 

Methods inside a class:

1. What is a Method?

  • A method is a function inside a class.

  • It defines behaviors or actions that objects created from the class can perform.

  • Think of it like what the object can “do”.

2. Syntax

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

  greet() {
    console.log(`Hi, I'm ${this.name}`);
  }

  birthday() {
    this.age += 1;
    console.log(`Happy Birthday! \({this.name} is now \){this.age} years old.`);
  }
}
  • greet() : makes the person introduce themselves

  • birthday() : increases the age by 1

3. Using Methods

const person1 = new Person("Mohit", 25);

person1.greet();    
person1.birthday(); 
  • Methods automatically belong to the object’s prototype, not copied per object.

  • This is memory-efficient if you create many objects from the class.

4. Real-world Analogy

OOP Concept Analogy
Property Age, Name, Color of a car
Method Actions a car can do: Drive(), Stop(), Honk()
class Car {
  constructor(brand, color) {
    this.brand = brand;
    this.color = color;
  }

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

  honk() {
    console.log(`${this.brand} says Beep! Beep!`);
  }
}

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

Output:

Toyota is driving
Toyota says Beep! Beep!

=== Code Execution Successful ===
  • drive() and honk() are methods that define behavior, not just data.

Basic idea of encapsulation:

1. What is Encapsulation?

  • Encapsulation is the practice of keeping the internal details of an object hidden and exposing only what is necessary.

  • In simpler terms: “Hide the private stuff, show only what’s needed.”

  • It helps protect data from accidental changes and makes your code more organized and secure.

2. Real-world Analogy

Think of a TV remote:

  • You see buttons (exposed functions) : you can press them to turn on/off, change volume, switch channels.

  • You don’t see the internal circuits (hidden data) : you don’t need to know how it works inside.

The remote encapsulates the complexity.

3. Encapsulation in JavaScript

In modern JS (ES6+), we use private fields with # to hide properties:

class Person {
  #salary;  

  constructor(name, age, salary) {
    this.name = name;     
    this.age = age;      
    this.#salary = salary; 
  }

  showSalary() {
    console.log(`\({this.name}'s salary is \){this.#salary}`);
  }
}

const person1 = new Person("Mohit", 25, 50000);

console.log(person1.name); 

person1.showSalary(); 

Output:

Mohit
Mohit's salary is 50000

=== Code Execution Successful ===
  • #salary is private, cannot be accessed directly outside the class.

  • showSalary() is public, the only way to see it.

4. Why Use Encapsulation?

  1. Data Protection : prevents accidental changes from outside.

  2. Controlled Access : you decide how the data can be read or modified.

  3. Better Maintenance : object manages its own state.

Assignment Idea:

1. Create the Student Class:

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

  printDetails() {
    console.log(`Student Name: \({this.name}, Age: \){this.age}`);
  }
}
  • constructor : sets name and age for each student.

  • printDetails() : method to display the student’s information.

2. Create Multiple Student Objects:

const student1 = new Student("Mohit", 25);
const student2 = new Student("Palak", 23);
const student3 = new Student("Rohan", 22);

3. Use the Method:

student1.printDetails(); 
student2.printDetails(); 
student3.printDetails(); 

4. Optional: Loop Through Multiple Students:

const students = [
  new Student("Amit", 24),
  new Student("Neha", 21),
  new Student("Sakshi", 23)
];

students.forEach(student => student.printDetails());

Output:

Student Name: Amit, Age: 24
Student Name: Neha, Age: 21
Student Name: Sakshi, Age: 23

Conclusion:

Object-Oriented Programming (OOP) in JavaScript is a way of structuring code around objects, which represent real-world entities with properties (data) and methods (behaviors).

Key takeaways:

  1. Classes and Objects

    • A class is a blueprint for creating objects.

    • An object is an instance of a class with its own unique data.

  2. Constructor Method

    • The constructor initializes an object’s properties automatically when it’s created.
  3. Methods Inside Classes

    • Methods define actions objects can perform, promoting reusability and organization.
  4. Encapsulation

    • Keeps the internal details of objects private, exposing only what’s necessary.

    • Helps protect data and provides controlled access.

  5. Inheritance and Polymorphism (Advanced)

    • Classes can inherit properties and methods from other classes.

    • Methods can behave differently in child classes (polymorphism).

Understanding Object-Oriented Programming in JavaScript