Java

Object Oriented Programming in JavaScript

Object Oriented Programming (OOP) is a programming paradigm that allows developers to structure code using objects, classes, and methods. In JavaScript, OOP helps in building scalable and maintainable applications by organizing code around objects rather than functions alone. This guide covers everything from core concepts to real-world examples, ideal for beginners and intermediate learners.

What is Object Oriented Programming in JavaScript?

JavaScript is a multi-paradigm language, supporting both procedural and object-oriented programming. Object Oriented Programming in JavaScript revolves around creating objects that contain both data (properties) and behavior (methods).

Key concepts of JavaScript OOP include:

  • Classes and Objects
  • Encapsulation
  • Inheritance
  • Polymorphism

Classes and Objects in JavaScript

Classes and objects are fundamental concepts in Object Oriented Programming in JavaScript. They allow developers to create reusable code structures and represent real-world entities in a program.

What is a Class?

A class in JavaScript is a blueprint for creating objects. It defines the properties (data) and methods (functions) that the objects created from it will have. Classes were introduced in ES6 to simplify object-oriented programming.

Basic Syntax of a Class

// Define a class class Person { constructor(name, age) { this.name = name; // Property this.age = age; // Property } // Method greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } // Create an object const john = new Person("John", 25); john.greet(); // Output: Hello, my name is John and I am 25 years old.

What is an Object?

An object is an instance of a class. It contains real values assigned to the properties defined by the class and can use the class methods. Objects represent real-world entities in your code.

Example: Creating Multiple Objects

class Car { constructor(make, model, year) { this.make = make; this.model = model; this.year = year; } displayInfo() { console.log(`${this.make} ${this.model} (${this.year})`); } } const car1 = new Car("Toyota", "Corolla", 2020); const car2 = new Car("Honda", "Civic", 2022); car1.displayInfo(); // Output: Toyota Corolla (2020) car2.displayInfo(); // Output: Honda Civic (2022)

 Points About Classes and Objects

  • Classes are templates for creating objects.
  • Objects are instances of classes with actual data.
  • Methods in a class define the behavior of objects.
  • Classes support encapsulation, hiding implementation details from the outside.
  • Objects allow reuse of code and maintainable program structure.

Use Case

Imagine building a library management system. Each Book can be an object with properties like title, author, and ISBN, and methods like borrow() and returnBook(). The Book class is the blueprint, and each individual book is an object.

class Book { constructor(title, author, ISBN) { this.title = title; this.author = author; this.ISBN = ISBN; this.isBorrowed = false; } borrow() { if (!this.isBorrowed) { this.isBorrowed = true; console.log(`${this.title} has been borrowed.`); } else { console.log(`${this.title} is already borrowed.`); } } returnBook() { this.isBorrowed = false; console.log(`${this.title} has been returned.`); } } const book1 = new Book("1984", "George Orwell", "12345"); book1.borrow(); // Output: 1984 has been borrowed. book1.returnBook(); // Output: 1984 has been returned.

Core Concepts of JavaScript OOP

1. Classes in JavaScript

Classes are blueprints for creating objects with specific properties and methods. Introduced in ES6, they make OOP in JavaScript easier and more intuitive.

// Define a class class Person { constructor(name, age) { this.name = name; this.age = age; } greet() { console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`); } } // Create an object const john = new Person("John", 30); john.greet(); // Output: Hello, my name is John and I am 30 years old.

2. Encapsulation in JavaScript

Encapsulation allows data to be hidden from outside access. This is often achieved using private fields or getter/setter methods.

class BankAccount { #balance; // private property constructor(initialBalance) { this.#balance = initialBalance; } deposit(amount) { this.#balance += amount; } getBalance() { return this.#balance; } } const account = new BankAccount(1000); account.deposit(500); console.log(account.getBalance()); // Output: 1500

3. Inheritance in JavaScript

Inheritance allows a class to inherit properties and methods from another class, promoting code reuse.

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.

4. Polymorphism in JavaScript

Polymorphism allows methods to behave differently based on the object calling them.

class Shape { area() { console.log("Calculating area..."); } } class Circle extends Shape { constructor(radius) { super(); this.radius = radius; } area() { console.log(`Circle area: ${Math.PI * this.radius * this.radius}`); } } class Square extends Shape { constructor(side) { super(); this.side = side; } area() { console.log(`Square area: ${this.side * this.side}`); } } const circle = new Circle(5); const square = new Square(4); circle.area(); // Output: Circle area: 78.53981633974483 square.area(); // Output: Square area: 16

 Examples of JavaScript OOP

JavaScript OOP is widely used in:

  • Web applications (e.g., React components as objects)
  • Game development (entities like players, enemies, and items)
  • Financial systems (bank accounts, transactions)
  • UI component libraries (buttons, forms, modals)

Practical Example: Managing a Library

class Book { constructor(title, author) { this.title = title; this.author = author; } } class Library { constructor() { this.books = []; } addBook(book) { this.books.push(book); } listBooks() { this.books.forEach(book => console.log(`${book.title} by ${book.author}`)); } } const myLibrary = new Library(); myLibrary.addBook(new Book("1984", "George Orwell")); myLibrary.addBook(new Book("To Kill a Mockingbird", "Harper Lee")); myLibrary.listBooks(); // Output: // 1984 by George Orwell // To Kill a Mockingbird by Harper Lee

Benefits of Object Oriented Programming in JavaScript

Benefit Description
Modularity Code is organized into classes and objects, making it easier to manage.
Reusability Inheritance allows code reuse across different classes.
Maintainability Encapsulation keeps internal logic private, reducing bugs.
Scalability OOP structure supports larger applications with complex functionality.


Object Oriented Programming in JavaScript is a powerful approach for writing clean, reusable, and maintainable code. By mastering classes, objects, inheritance, encapsulation, and polymorphism, developers can build robust applications ranging from simple web apps to complex enterprise systems. Whether you are a beginner or intermediate JavaScript learner, understanding OOP is crucial for professional development.

FAQs on JavaScript Object Oriented Programming

1. What is the difference between a class and an object in JavaScript?

A class is a blueprint for creating objects, while an object is an instance of a class. Classes define properties and methods, and objects hold actual data.

2. Can JavaScript support multiple inheritance?

JavaScript does not support multiple inheritance directly, but you can achieve similar behavior using mixins or composition patterns.

3. What are private fields in JavaScript OOP?

Private fields, denoted by a prefix, allow encapsulation of data, preventing access from outside the class.

4. Why use polymorphism in JavaScript?

Polymorphism allows objects of different classes to be treated uniformly while still executing behavior specific to their type. This improves code flexibility and maintainability.

5. How is OOP different from procedural programming in JavaScript?

Procedural programming focuses on writing functions and executing sequences of instructions, whereas OOP organizes code into objects that encapsulate both data and behavior, promoting reusability and scalability.

line

Copyrights © 2024 letsupdateskills All rights reserved