Skip to main content

Command Palette

Search for a command to run...

Understanding Object-Oriented Programming in JavaScript

Updated
10 min read
Understanding Object-Oriented Programming in JavaScript

What Object-Oriented Programming (OOP) means

Object-Oriented Programming (OOP) is a programming paradigm based on the concept of "objects"—data structures that encapsulate both data (attributes) and behaviors (methods). It models software around real-world entities, improving code reusability, scalability, and maintainability by organizing code into classes and objects.

Key features and concepts of OOP include:

  • Class: A blueprint or template for creating objects, defining the data and methods common to all objects of that type.

  • Object: An instance of a class, representing a specific, usable entity in the program.

  • Encapsulation: Binding data (variables) and methods (functions) together and hiding internal state, only exposing a public interface, which enhances security.

  • Inheritance: A mechanism for creating new classes (child) that inherit properties and behaviors from existing classes (parent), facilitating code reuse.

  • Polymorphism: The ability of different classes to be treated as instances of the same class through a common interface, often allowing one method to have multiple implementations.

  • Abstraction: Hiding complex implementation details and showing only the necessary features of an object.

Popular OOP languages include Java, Python, C++, and C#.

Real-world analogy (blueprint → objects)

A blueprint represents a class (the template/design), while the physical object created from it represents an object (the instance). The blueprint defines structure, properties, and behaviors, but does not exist as a usable item until an object is created from it.

Key Analogies:

  • Car Blueprint vs. Actual Car: The blueprints for a Honda City define its wheels and engine, but it is not a driveable vehicle. The actual Honda City you park in your garage is the "object".

  • House Plan vs. Real House: An architect’s drawing is the blueprint/class, while the physical house with furniture and inhabitants is the object. Multiple houses can be built from one plan.

  • Cookie Cutter vs. Cookies: The cookie cutter represents the class defining the shape, while each cookie created represents an object.

Why this works:

  • Blueprint (Class): Defines structure: Number of rooms, floor layout, and features (e.g., has a door).

  • Object (Instance): The concrete entity: A specific house at a specific address with its own data (e.g., painted blue).

  • Reuse: You can build thousands of houses (objects) from one set of plans (class).

What is a class in JavaScript

A class in JavaScript is a blueprint or template used to create objects. Introduced in ECMAScript 2015 (ES6), it provides a cleaner, more structured way to handle object-oriented programming (OOP) compared to older prototype-based methods.

Technically, a class is a "special function". While it looks like classes in languages like Java or C++, it is actually syntactic sugar built on top of JavaScript's existing prototypal inheritance system.

Key Components of a Class

  • Keyword class: Used to declare the class.

  • constructor() method: A special method that runs automatically when you create a new object (instance) of the class. It is primarily used to initialize properties.

  • Methods: Functions defined inside the class that describe the behaviors the objects will have.

  • new keyword: Used to "instantiate" or create a specific object from the class template.

javascript

class Car {
  constructor(brand, year) {
    this.brand = brand; // Property
    this.year = year;
  }

  displayInfo() { //Method
return `This is a \({this.brand} from \){this.year}.`;
  }
}

// Creating an object (instance)
const myCar = new Car("Ford", 2024);
console.log(myCar.displayInfo()); 

Core Features

  • Inheritance: You can create a "subclass" that inherits properties and methods from a parent class using the extends keyword.

  • Encapsulation: Bundles data (properties) and methods into a single unit, and supports private fields (using #) to hide sensitive data.

  • Static Methods: Methods defined with the static keyword belong to the class itself rather than any specific object instance.

Creating objects using classes

To create objects using classes in JavaScript, you define a blueprint using the class keyword and then instantiate it with the new keyword.

1. Basic Syntax

A class serves as a template that defines the structure (properties) and behavior (methods) of the objects created from it.

javascript

class Car {
  // 1. The constructor initializes properties
  constructor(brand, year) {
    this.brand = brand;
    this.year = year;
  }

  // 2. Class methods define behavior
  displayInfo() {
    return `\({this.brand} was made in \){this.year}`;
  }
}

// 3. Create objects (instances) using 'new'
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);

console.log(myCar1.displayInfo()); // Output: Ford was made in 2014

2. Key Components

  • The class Keyword: Introduced in ES6, it provides a cleaner, more structured way to handle object-oriented programming compared to older constructor functions.

  • The constructor Method: A special method executed automatically when a new object is created. It is used to initialize the object's properties.

  • Methods: Functions defined within the class body (without using the function keyword) that are shared by all instances of that class.

  • The this Keyword: Refers to the specific object instance being created or manipulated, allowing it to track its own unique state.

  • Static Properties/Methods: Using the static keyword defines properties that belong to the class itself rather than any individual object instance.

3. Why Use Classes?

  • Efficiency: You can create many similar objects from one blueprint without repeating code.

  • Readability: It offers a familiar syntax for those coming from other object-oriented languages.

  • Inheritance: Classes make it easy to create subclasses that inherit properties and methods from a parent class.

Constructor method

In JavaScript, a constructor is a special method used to create and initialize objects. It is automatically called when you create a new instance of a class using the new keyword.

Key Characteristics

  • Initialization: Its primary purpose is to set up initial values for an object's properties.

  • Automatic Execution: You don't call it like a regular method; it runs automatically when you instantiate a class.

  • Singularity: A class can have only one constructor method. Including more than one will result in a SyntaxError.

  • Inheritance: In a derived class (one that extends another), the constructor must call super() before accessing this to initialize the parent class.

Syntax Example

Modern JavaScript (ES6+) uses the class syntax for constructors:

javascript

class Car {
  constructor(brand, year) {
    this.brand = brand; // Property initialization
    this.year = year;
  }
}

// Creating a new instance
const myCar = new Car("Tesla", 2024);
console.log(myCar.brand); // Output: Tesla

Constructor Functions (Traditional Method)

Before ES6, JavaScript used regular functions as constructors, often following the Pascal Case naming convention to distinguish them:

javascript

function User(name) {
  this.name = name;
}

const user1 = new User("Alice");

Built-in Constructors

JavaScript also includes built-in constructors for native objects:

  • new Date(): Creates a new date object.

  • new Array(): Creates a new array.

  • new Map(): Creates a new Map object.

  • new Object(): Creates a generic object.

Methods inside a class

In JavaScript, methods are functions defined inside a class to define the behavior of that class's objects. They are written within the class body without using the function keyword.

Common Method Types

  • Constructor Method: A special method (constructor()) used to create and initialize objects. Every class can have only one.

  • Instance Methods: Standard methods available to all instances created from the class. They can access object data using the this keyword.

  • Static Methods: Methods defined with the static keyword. These are called directly on the class itself rather than on instances, and are often used for utility functions.

  • Getters and Setters: Special methods (using get and set) that allow you to read or update private or calculated properties as if they were simple variables.

  • Private Methods: Methods prefixed with a hashtag (e.g., #calculateInternal()) that are only accessible from within the class itself.

javascript

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

  // Instance Method
  present() {
    return 'I have a ' + this.carname;
  }

  // Static Method
  static hello() {
    return "Hello!";
  }
}

const myCar = new Car("Ford");
console.log(myCar.present()); // "I have a Ford"
console.log(Car.hello());     // "Hello!" (called on the class)

Key Differences from Standard Functions

  • No Commas: Unlike object literals, class methods are not separated by commas.

  • Strict Mode: Class bodies are always executed in "strict mode" by default.

  • Prototype-based: Instance methods are stored on the class's prototype, meaning they are shared among all instances to save memory.

Basic idea of encapsulation

Encapsulation in JavaScript is the practice of bundling data (properties) and the methods that operate on that data into a single unit (like an object or class) while restricting direct access to the internal details. Think of it like a capsule that hides the complex "medicine" inside and only provides a simple shell for you to interact with.

The main goals of encapsulation are:

  • Data Protection: Preventing external code from accidentally or intentionally corrupting internal state.

  • Controlled Access: Forcing users to interact with data through specific methods (like getters and setters) that can include validation.

  • Information Hiding: Hiding implementation details so you can change the internal code later without breaking everything else.

How to Achieve Encapsulation in JavaScript

Historically, JavaScript didn't have strict "private" modifiers, but modern versions and common patterns provide several ways to implement it:

  • Private Class Fields (#): Modern JavaScript (ES2022+) allows you to prefix a property or method with a # to make it strictly private.

    javascript

    class BankAccount {
      #balance = 0; // Private field
    
      deposit(amount) {
        if (amount > 0) this.#balance += amount;
      }
    
      getBalance() {
        return this.#balance; // Controlled access
      }
    }
    

Closures: A classic technique where variables are defined inside a function scope and only exposed through returned functions.

javascript

function createCounter() {
  let count = 0; // "Private" variable
  return {
    increment: () => count++,
    getCount: () => count
  };
}
  • The Underscore Convention (_): Before private fields existed, developers used a leading underscore (e.g., _balance) to signal that a property was "intended" to be private and should not be accessed directly.

  • Modules: Using ES Modules allows you to keep variables and functions private to a file unless they are explicitly exported.

Create a class called Student

Basic Student class

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

  // Method to display details
  getDetails() {
    return `Name: \({this.name}, Age: \){this.age}, Grade: ${this.grade}`;
  }

  // Method to update grade
  updateGrade(newGrade) {
    this.grade = newGrade;
  }
}

▶️ Using the class

const student1 = new Student("Hitakshi", 20, "A");

console.log(student1.getDetails());
// Output: Name: Hitakshi, Age: 20, Grade: A

student1.updateGrade("A+");
console.log(student1.getDetails());
// Output: Name: Hitakshi, Age: 20, Grade: A+

🧠 What’s happening

  • constructor() → initializes object properties

  • this → refers to current object

  • Methods → functions inside class


⚡ Add more features (advanced)

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

  getAverage() {
    const sum = this.marks.reduce((a, b) => a + b, 0);
    return sum / this.marks.length;
  }

  hasPassed() {
    return this.getAverage() >= 40;
  }
}

const s = new Student("Rahul", [50, 60, 70]);
console.log(s.getAverage()); // 60
console.log(s.hasPassed());  // true