DEV Community

Sai Swaroop Bijinapalli
Sai Swaroop Bijinapalli

Posted on

About Prototype-Chain

Object-Oriented JavaScript (OOP): A Complete Guide with Examples

Introduction

Object-Oriented Programming (OOP) is one of the most popular programming paradigms used to organize code into objects. An object contains data (properties) and behavior (methods).

JavaScript is a prototype-based object-oriented language. Unlike Java or C++, which use class-based inheritance, JavaScript uses prototypes to inherit properties and methods. However, since ES6, JavaScript introduced the class syntax, making OOP easier to read and write.

Learning OOP in JavaScript helps you write code that is:

  • Reusable
  • Modular
  • Easy to maintain
  • Easy to extend
  • Easier to understand in large applications

What is Object-Oriented Programming (OOP)?

Object-Oriented Programming is a programming style where we represent real-world entities as objects.

An object contains:

  • Properties (State) → Information about the object
  • Methods (Behavior) → Actions the object can perform

For example, consider a Car.

Car

Properties
-----------
Brand
Color
Speed

Methods
-----------
Start()
Stop()
Accelerate()
Brake()
Enter fullscreen mode Exit fullscreen mode

In JavaScript, we can represent it like this:

```javascript id="lmn421"
const car = {
brand: "Tesla",
color: "Black",
speed: 0,

start() {
    console.log("Car Started");
},

accelerate() {
    this.speed += 20;
    console.log(this.speed);
}
Enter fullscreen mode Exit fullscreen mode

};

car.start();
car.accelerate();




Output



```id="n2sk7h"
Car Started
20
Enter fullscreen mode Exit fullscreen mode

Here:

  • brand, color, and speed are properties.
  • start() and accelerate() are methods.

Why Do We Need OOP?

Imagine creating 100 students.

Without OOP:

```javascript id="5t0nqk"
const student1 = {
name: "Sai",
age: 20
};

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

const student3 = {
name: "John",
age: 22
};




You would repeat the same structure many times.

Instead, OOP allows you to create a blueprint.

---

# Constructor Function

Before ES6 classes, JavaScript used constructor functions.



```javascript id="z73mbe"
function Student(name, age) {
    this.name = name;
    this.age = age;
}

const s1 = new Student("Sai", 20);
const s2 = new Student("Ram", 21);

console.log(s1);
console.log(s2);
Enter fullscreen mode Exit fullscreen mode

Output

Student { name: "Sai", age: 20 }

Student { name: "Ram", age: 21 }
Enter fullscreen mode Exit fullscreen mode

The constructor acts as a blueprint for creating multiple objects.


ES6 Classes

JavaScript introduced classes in ES6.

```javascript id="9k2m8c"
class Student {

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

study() {
    console.log(this.name + " is studying");
}
Enter fullscreen mode Exit fullscreen mode

}

const s1 = new Student("Sai", 20);

s1.study();




Output



```id="gl6x5y"
Sai is studying
Enter fullscreen mode Exit fullscreen mode

Although this looks like Java or C++, classes internally use JavaScript's prototype system.


Four Pillars of OOP

Object-Oriented Programming is based on four major principles:

Object-Oriented Programming

        │

 ┌──────┼────────┐
 │      │        │
 ▼      ▼        ▼
Encapsulation
Inheritance
Polymorphism
Abstraction
Enter fullscreen mode Exit fullscreen mode

Let's understand each one.


1. Encapsulation

What is Encapsulation?

Encapsulation means keeping data and the methods that operate on that data together inside one object, while also controlling access to that data.

Think of a bank account.

Bank Account

Balance

Deposit()

Withdraw()

GetBalance()
Enter fullscreen mode Exit fullscreen mode

Users should not directly change the balance.

Instead, they should use methods like deposit() or withdraw().


Example Using Private Fields

```javascript id="9wv9d8"
class BankAccount {

#balance = 0;

deposit(amount) {
    this.#balance += amount;
}

withdraw(amount) {
    this.#balance -= amount;
}

getBalance() {
    return this.#balance;
}
Enter fullscreen mode Exit fullscreen mode

}

const account = new BankAccount();

account.deposit(1000);
account.withdraw(200);

console.log(account.getBalance());




Output



```id="z3pygk"
800
Enter fullscreen mode Exit fullscreen mode

Trying this:

```javascript id="dn3x1x"
console.log(account.#balance);




Results in an error because `#balance` is private.

Benefits:

* Protects data
* Prevents accidental modification
* Improves security

---

# 2. Inheritance

## What is Inheritance?

Inheritance allows one class to acquire the properties and methods of another class.

Real-life example:



```id="elz6vy"
Animal

eat()

sleep()

      ▲

      │

Dog

bark()
Enter fullscreen mode Exit fullscreen mode

The Dog class automatically gets the methods of Animal.


Example

```javascript id="l5v0qo"
class Animal {

eat() {
    console.log("Eating");
}
Enter fullscreen mode Exit fullscreen mode

}

class Dog extends Animal {

bark() {
    console.log("Barking");
}
Enter fullscreen mode Exit fullscreen mode

}

const dog = new Dog();

dog.eat();
dog.bark();




Output



```id="v7h7ew"
Eating

Barking
Enter fullscreen mode Exit fullscreen mode

Inheritance avoids code duplication.


Using super()

The super keyword calls the parent class constructor.

```javascript id="klyp92"
class Animal {

constructor(name) {
    this.name = name;
}
Enter fullscreen mode Exit fullscreen mode

}

class Dog extends Animal {

constructor(name, breed) {
    super(name);
    this.breed = breed;
}
Enter fullscreen mode Exit fullscreen mode

}

const dog = new Dog("Tom", "Labrador");

console.log(dog);




Output



```id="tht91x"
Dog {

name: "Tom",

breed: "Labrador"

}
Enter fullscreen mode Exit fullscreen mode

3. Polymorphism

What is Polymorphism?

Polymorphism means one interface, many forms.

Different objects can implement the same method differently.


Example

```javascript id="e8iqcx"
class Animal {

speak() {
    console.log("Animal Sound");
}
Enter fullscreen mode Exit fullscreen mode

}

class Dog extends Animal {

speak() {
    console.log("Bark");
}
Enter fullscreen mode Exit fullscreen mode

}

class Cat extends Animal {

speak() {
    console.log("Meow");
}
Enter fullscreen mode Exit fullscreen mode

}

const dog = new Dog();
const cat = new Cat();

dog.speak();
cat.speak();




Output



```id="t9hvo8"
Bark

Meow
Enter fullscreen mode Exit fullscreen mode

Both classes have a speak() method, but each behaves differently.

This is method overriding, one of the most common forms of polymorphism.


4. Abstraction

What is Abstraction?

Abstraction means showing only essential features while hiding internal implementation details.

Example:

When driving a car, you use the steering wheel, accelerator, and brake. You don't need to know how the engine or transmission works internally.


Example

```javascript id="b9u74f"
class CoffeeMachine {

makeCoffee() {
    this.#boilWater();
    console.log("Coffee Ready");
}

#boilWater() {
    console.log("Boiling Water...");
}
Enter fullscreen mode Exit fullscreen mode

}

const machine = new CoffeeMachine();

machine.makeCoffee();




Output



```id="yb3poh"
Boiling Water...

Coffee Ready
Enter fullscreen mode Exit fullscreen mode

Users only call makeCoffee(). The internal boiling process is hidden.


Prototype-Based OOP

Even though JavaScript has classes, everything is still based on prototypes.

```javascript id="fxz6eh"
class Person {

constructor(name) {
    this.name = name;
}

greet() {
    console.log("Hello");
}
Enter fullscreen mode Exit fullscreen mode

}




Internally, JavaScript creates:



```javascript id="sx6uyj"
function Person(name) {
    this.name = name;
}

Person.prototype.greet = function () {
    console.log("Hello");
};
Enter fullscreen mode Exit fullscreen mode

This is why JavaScript is called a prototype-based language.


Object Relationships

Student Object

name

age

study()

        │

        ▼

Student.prototype

study()

        │

        ▼

Object.prototype

toString()

hasOwnProperty()

valueOf()

        │

        ▼

null
Enter fullscreen mode Exit fullscreen mode

Class Example

```javascript id="z93vrl"
class Employee {

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

display() {
    console.log(this.name, this.salary);
}
Enter fullscreen mode Exit fullscreen mode

}

const emp1 = new Employee("Sai", 50000);
const emp2 = new Employee("Ram", 70000);

emp1.display();
emp2.display();




Output



```id="qg64t9"
Sai 50000

Ram 70000
Enter fullscreen mode Exit fullscreen mode

Advantages of OOP

  • Promotes code reusability through inheritance.
  • Improves maintainability by organizing related data and behavior.
  • Enhances security with encapsulation.
  • Simplifies large projects by dividing functionality into objects.
  • Makes applications easier to extend and scale.

OOP vs Procedural Programming

Procedural Programming Object-Oriented Programming
Focuses on functions Focuses on objects
Data and functions are separate Data and methods are grouped together
Less reusable Highly reusable
Difficult to maintain in large projects Easier to maintain and scale
No inheritance Supports inheritance

Interview Questions

What is OOP?

Object-Oriented Programming is a programming paradigm that organizes code into objects containing properties and methods.


What are the four pillars of OOP?

  • Encapsulation
  • Inheritance
  • Polymorphism
  • Abstraction

Is JavaScript object-oriented?

Yes. JavaScript is an object-oriented language that uses prototype-based inheritance. ES6 introduced class syntax, but it still works on top of prototypes.


What is the difference between a class and an object?

A class is a blueprint for creating objects.

An object is an instance of a class.


What is inheritance?

Inheritance allows one class to acquire the properties and methods of another class, reducing code duplication.


What is encapsulation?

Encapsulation groups data and methods together while controlling access to internal data, often using private fields.


What is polymorphism?

Polymorphism allows the same method name to have different implementations in different classes.


What is abstraction?

Abstraction hides internal implementation details and exposes only the necessary functionality.


Conclusion

Object-Oriented Programming is a powerful approach for building scalable and maintainable applications. JavaScript supports OOP through its prototype system and provides a cleaner class syntax to make development easier.

Understanding objects, classes, prototypes, and the four OOP pillars—Encapsulation, Inheritance, Polymorphism, and Abstraction—will help you write cleaner code, build reusable components, and confidently tackle real-world JavaScript projects. While the syntax may resemble other object-oriented languages, remember that JavaScript's true foundation is prototype-based inheritance, making it both flexible and unique.

Top comments (0)