learn2kode.in

What Is JavaScript OOP?

JavaScript Object-Oriented Programming (OOP) is a programming style that organizes code using objects and classes. Instead of writing scattered functions, OOP helps you group related data and behavior together, making your code easier to maintain, scale, and reuse.
JavaScript uses prototype-based OOP, but modern JavaScript (ES6+) introduced the class syntax, making OOP easier for beginners to understand.

Why Use OOP in JavaScript?

Using OOP in JavaScript helps you:
OOP is widely used in frontend frameworks, Node.js backend development, and game development.

Core OOP Concepts in JavaScript

JavaScript OOP is based on four main principles:
Let’s explore each one with simple explanations.
Objects in JavaScript
An object is a collection of properties and methods.
const user = {
  name: "learn2kode",
  role: "Developer",
  greet() {
    return `Hello, I am ${this.name}`;
  }
};
Objects represent real-world entities like users, products, or orders.
Classes in JavaScript
A class is a blueprint for creating objects. Classes were introduced in ES6.
class User {
  constructor(name, role) {
    this.name = name;
    this.role = role;
  }

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

const user1 = new User("learn2kode", "Developer");
Classes make JavaScript OOP easier to read and maintain.
Inheritance in JavaScript
Inheritance allows one class to use properties and methods of another class.
class Admin extends User {
  accessLevel() {
    return "Full Access";
  }
}
Inheritance promotes code reuse and better structure.
Encapsulation in JavaScript
Encapsulation means hiding internal data and exposing only what is necessary.
class Account {
  #balance = 0;

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

  getBalance() {
    return this.#balance;
  }
}
This prevents direct access to sensitive data.
Polymorphism in JavaScript
Polymorphism allows methods to behave differently based on the object calling them.
class Animal {
  speak() {
    return "Animal sound";
  }
}

class Dog extends Animal {
  speak() {
    return "Bark";
  }
}
Same method name, different behavior.
JavaScript Prototypes and OOP
Behind the scenes, JavaScript uses prototypes for inheritance.
User.prototype.sayHi = function () {
  return "Hello!";
};
Understanding prototypes helps you master advanced JavaScript OOP concepts.

When to Use OOP in JavaScript?

JavaScript OOP is ideal when:
For small scripts, OOP may not be necessary.

JavaScript OOP vs Functional Programming

JavaScript supports both OOP and functional programming. OOP focuses on objects and state, while functional programming focuses on functions and immutability.
Modern JavaScript applications often use a hybrid approach.

Final Thoughts

JavaScript OOP helps you write structured, scalable, and maintainable code. By mastering objects, classes, inheritance, and encapsulation, you’ll be better prepared to build real-world JavaScript applications.