Skip to main content
JavaScript Basics
CHAPTER 22 Beginner

JavaScript Classes and OOP

Updated: May 12, 2026
30 min read

# JavaScript Classes and OOP

Up until now, whenever we needed an object, we created it manually using {}. But what if you are building a school management system and you need to create 500 Student objects? Typing out { name: "...", age: ... } 500 times is impossible.

In this chapter, we will learn Object-Oriented Programming (OOP) by creating Classes—blueprints for generating objects automatically.

1. Introduction

A Class is a template for creating objects. It defines the properties and methods that the created objects (called Instances) will have.

Before ES6, JavaScript handled OOP using "Constructor Functions" and the Prototype chain, which was confusing for developers coming from languages like Java or C++. ES6 introduced the class keyword to make OOP in JavaScript cleaner and more intuitive.

2. Learning Objectives

By the end of this chapter, you will be able to:

  • Define a Class using the class keyword.
  • Understand and use the constructor() method.
  • Add methods to a Class.
  • Instantiate new objects using the new keyword.
  • Understand Inheritance using the extends and super keywords.
  • Build a Student Management System mini-project.

3. Class Syntax and the Constructor

To create a class, use the class keyword followed by the name of the class (Class names should always start with a Capital Letter).

Inside the class, you MUST add a method named constructor(). This is a special function that runs automatically every time a new object is created from this class. It is used to initialize the object's properties.

javascript
1234567
// Syntax
class ClassName {
    constructor(param1, param2) {
        this.property1 = param1;
        this.property2 = param2;
    }
}

4. Creating Instances (The new keyword)

A class does nothing on its own. It is just a blueprint. To actually build an object from it, you must use the new keyword.

javascript
12
// Example
const myObject = new ClassName("Value 1", "Value 2");

---

5. Real-world Examples & Code Snippets

Example 1: Creating a Basic Class

javascript
1234567891011121314
// Example JavaScript
class Car {
    constructor(brand, year) {
        this.brand = brand;
        this.year = year;
    }
}

// Instantiate two different cars
const myCar = new Car("Ford", 2014);
const yourCar = new Car("Audi", 2022);

console.log(myCar.brand);   // Output: Ford
console.log(yourCar.brand); // Output: Audi

Example 2: Adding Methods to a Class

You can add standard methods inside the class. Notice you do NOT use the function keyword for class methods.

javascript
12345678910111213141516171819
// Example JavaScript
class User {
    constructor(name, email) {
        this.name = name;
        this.email = email;
    }

    // A class method
    login() {
        console.log(`${this.name} has logged in.`);
    }

    logout() {
        console.log(`${this.name} has logged out.`);
    }
}

const user1 = new User("John", "john@test.com");
user1.login(); // Output: John has logged in.

Example 3: Method Chaining

If you return this at the end of a method, you can chain multiple methods together!

javascript
123456789101112131415161718192021
// Example JavaScript
class Player {
    constructor(name) {
        this.name = name;
        this.score = 0;
    }

    addPoints() {
        this.score += 10;
        return this; // Crucial for chaining!
    }

    printScore() {
        console.log(`${this.name}: ${this.score} pts`);
        return this;
    }
}

const p1 = new Player("Mario");
// Chain them together!
p1.addPoints().addPoints().printScore(); // Output: Mario: 20 pts

Example 4: Inheritance (extends)

Inheritance allows a new class to inherit all the properties and methods of an existing class. It is excellent for code reusability.

javascript
123456789101112131415161718192021
// Example JavaScript
// 1. The Parent Class
class Animal {
    constructor(name) {
        this.name = name;
    }
    eat() {
        console.log(`${this.name} is eating.`);
    }
}

// 2. The Child Class
class Dog extends Animal {
    bark() {
        console.log(`${this.name} says Woof!`);
    }
}

const myDog = new Dog("Rex");
myDog.eat();  // Inherited from Animal! Output: Rex is eating.
myDog.bark(); // Output: Rex says Woof!

Example 5: The super Keyword

If a child class has its own constructor, it MUST call super() before it can use this. super() calls the constructor of the parent class.

javascript
1234567891011121314151617181920
// Example JavaScript
class Employee {
    constructor(name) {
        this.name = name;
    }
}

class Manager extends Employee {
    constructor(name, department) {
        super(name); // Passes 'name' up to the Employee constructor
        this.department = department; // Now we can set child-specific properties
    }
    
    getDetails() {
        console.log(`${this.name} manages ${this.department}`);
    }
}

const boss = new Manager("Alice", "Sales");
boss.getDetails(); // Output: Alice manages Sales

Example 6: Static Methods

Static methods are attached to the Class itself, NOT to the individual objects (instances) created from it. They are often used for utility functions.

javascript
123456789101112
// Example JavaScript
class MathHelper {
    static add(a, b) {
        return a + b;
    }
}

// We do NOT use the 'new' keyword! We call it directly on the Class.
console.log(MathHelper.add(5, 10)); // Output: 15

// const m = new MathHelper();
// m.add(5, 10); // ERROR! Instances cannot access static methods.

Example 7: Private Properties (Modern ES2022)

By prefixing a property with #, it becomes completely private and cannot be accessed from outside the class.

javascript
123456789101112131415161718
// Example JavaScript
class BankAccount {
    #balance; // Declare private field

    constructor(initialDeposit) {
        this.#balance = initialDeposit;
    }

    deposit(amount) {
        this.#balance += amount;
        console.log(`Deposited. New balance: $${this.#balance}`);
    }
}

const myAccount = new BankAccount(100);
myAccount.deposit(50); // Output: Deposited. New balance: $150

// console.log(myAccount.#balance); // SYNTAX ERROR: Private field!

---

6. Common Mistakes for Beginners

  1. 1. Forgetting this: Inside a class, if you want to access a property, you MUST use this.propertyName. If you just write propertyName, JS will look for a local variable and throw a ReferenceError.
  1. 2. Forgetting the new keyword: Calling const c = Car("Ford") without new will throw a TypeError: Class constructor cannot be invoked without 'new'.
  1. 3. Putting commas between methods: In an Object Literal {}, you separate properties and methods with commas. In a Class {}, there are NO commas between methods.

7. Best Practices

  • Capitalize Class names (class UserManager) to distinguish them from regular variables and functions.
  • Keep classes focused on a single entity. Don't create a GodClass that manages Users, Products, and Database Connections all at once.

8. Mini Project: Student Management System

Let's build a UI that instantiates objects from a Student class and displays them.

HTML:

html
123456789101112131415161718192021222324252627
<!-- Example HTML -->
<!DOCTYPE html>
<html>
<head>
    <style>
        /* Example CSS */
        body { font-family: sans-serif; padding: 20px; background: #fafafa;}
        .container { width: 350px; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        input { display: block; width: 90%; padding: 8px; margin-bottom: 10px;}
        button { background: #28a745; color: white; padding: 10px; width: 100%; border: none; cursor: pointer; margin-bottom: 15px;}
        .student-card { background: #e9ecef; padding: 10px; border-radius: 4px; margin-bottom: 10px;}
    </style>
</head>
<body>

    <div class="container">
        <h3>Add Student</h3>
        <input type="text" id="sName" placeholder="Student Name">
        <input type="text" id="sGrade" placeholder="Grade (A, B, C...)">
        <button onclick="enrollStudent()">Enroll</button>
        
        <div id="studentList"></div>
    </div>

    <script src="school.js"></script>
</body>
</html>

school.js:

javascript
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
// Example JavaScript

// 1. Define the Class Blueprint
class Student {
    constructor(name, grade) {
        this.name = name;
        this.grade = grade;
        this.enrolledDate = new Date().toLocaleDateString();
    }

    // Method to generate HTML for this specific student
    getCardHTML() {
        return `
            <div class="student-card">
                <strong>${this.name}</strong> - Grade: ${this.grade}
                <br><small>Enrolled: ${this.enrolledDate}</small>
            </div>
        `;
    }
}

// Global array to hold our instantiated objects
const roster = [];

function enrollStudent() {
    let nameVal = document.getElementById("sName").value;
    let gradeVal = document.getElementById("sGrade").value;

    if (nameVal === "" || gradeVal === "") return;

    // 2. Instantiate a NEW object from the Class
    let newStudent = new Student(nameVal, gradeVal);
    
    // 3. Save it to our database array
    roster.push(newStudent);

    // 4. Render UI
    renderRoster();
    
    // Clear inputs
    document.getElementById("sName").value = "";
    document.getElementById("sGrade").value = "";
}

function renderRoster() {
    let listDiv = document.getElementById("studentList");
    let html = "";
    
    for (let studentObj of roster) {
        // Call the method attached to the object!
        html += studentObj.getCardHTML();
    }
    
    listDiv.innerHTML = html;
}

9. Exercises

  1. 1. Create a Book class with a constructor that takes title and author.
  1. 2. Instantiate two different books using the new keyword.
  1. 3. Add a method read() to the Book class that console logs "You are reading [title]". Call this method on one of your instances.

10. MCQs (Multiple Choice Questions)

Q1: What special method runs automatically when a new class instance is created? A) init() B) start() C) constructor() D) build() *Answer: C*

Q2: Which keyword is used to create a child class from a parent class? A) inherits B) extends C) super D) childOf *Answer: B*

Q3: Which keyword is required to invoke a class and generate an object? A) create B) generate C) make D) new *Answer: D*

11. Interview Questions

Q: Explain the super keyword in JavaScript Classes. *A: The super keyword is used within a child class to call the constructor or methods of its parent class. If a child class has its own constructor, calling super() is strictly required before the this keyword can be used.*

Q: Are ES6 Classes actually real classes like in Java? *A: No. Under the hood, JavaScript is a "Prototype-based" language. ES6 classes are just "syntactic sugar" over JavaScript's existing prototype-based inheritance. They behave similarly, but the underlying engine implementation is entirely different from classical OOP languages.*

12. FAQs

Q: Do I have to use Classes? *A: No. Many modern developers prefer "Functional Programming" over OOP. For example, React heavily shifted away from Class Components to Functional Components in 2019. However, understanding classes is mandatory for understanding the wider JS ecosystem (like Node.js and Angular).*

13. Summary

  • Classes are blueprints for creating Objects.
  • constructor() sets up the object's initial data.
  • The new keyword builds the actual object (Instance).
  • extends creates a child class (Inheritance).
  • super() calls the parent's constructor.
  • Static methods belong to the class, not the instances.

14. Next Chapter Recommendation

You can now create complex objects and arrays using modern ES6 syntax. But how do we send this data to a database or receive it from a server? We can't send raw memory objects over the internet. In the next chapter, JavaScript JSON, we will learn how to serialize our data for the web.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·