Chapter 26 of 49

JavaScript Classes

Imagine you're building a college portal with hundreds of students. Each student has a name, a course, and the ability to introduce themselves. Writing an object literal for each one quickly gets repetitive:

const s1 = {
    name: "Kabir",
    course: "BCA",
    introduce() {
        console.log("Hi, I am " + this.name);
    }
};

const s2 = {
    name: "Meera",
    course: "B.Tech",
    introduce() {
        console.log("Hi, I am " + this.name);
    }
};
// ...and 498 more

We need a way to describe what a student looks like once, and then create as many students as we want. That's exactly what a class does.

What is a Class?

A class is a blueprint for creating objects. It defines the properties each object will have and the methods (functions) they can use.

Think of a class as a cookie cutter and the objects as cookies. You design the cutter once, then press out as many cookies as you like. Each cookie is separate, but they all have the same shape.

An object created from a class is called an instance of that class.

Classes were added to JavaScript in ES6 (2015). If you know Java or C++, the syntax will look familiar, but under the hood JavaScript classes are built on prototypes, which we'll explore in the next chapter.


Creating a Class

We create a class with the class keyword, and create instances with new:

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

    introduce() {
        console.log("Hi, I am " + this.name + " from " + this.course);
    }
}

const s1 = new Student("Kabir", "BCA");
const s2 = new Student("Meera", "B.Tech");

s1.introduce();
s2.introduce();

Output:

Hi, I am Kabir from BCA
Hi, I am Meera from B.Tech

Let's break it down:

  • class Student { ... } defines the blueprint. Class names start with a capital letter by convention.

  • constructor() is a special method that runs automatically when you write new Student(...). It sets up the new object.

  • Inside the constructor, this is the new object being created (Rule 5 from the this Keyword chapter).

  • introduce() is a method. Notice there's no function keyword and no commas between methods.

When we call new Student("Kabir", "BCA"):

1. A new empty object is created
2. constructor("Kabir", "BCA") runs with this = that new object
3. this.name = "Kabir", this.course = "BCA"
4. The object is returned and stored in s1
5. s1 can use every method defined in the class

If you don't write a constructor, JavaScript adds an empty one for you.


Methods Are Shared

Each instance has its own data (name, course), but methods are not copied into every object. All instances share a single copy of each method:

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

    introduce() {
        console.log("Hi, I am " + this.name);
    }
}

const s1 = new Student("Kabir");
const s2 = new Student("Meera");

console.log(s1.introduce === s2.introduce);
console.log(Object.keys(s1));

Output:

true
[ 'name' ]

(That's how Node.js prints the array ["name"].)

introduce isn't even one of s1's own properties. It lives in a shared place called the prototype, which saves memory when you have thousands of objects. The next chapter explains exactly how this works.


Class Fields

Properties that every instance should start with can be declared directly in the class body as class fields (standard since ES2022):

class Student {
    college = "City College"; // same starting value for everyone
    marks = 0;

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

const s1 = new Student("Kabir");
s1.marks = 85;

const s2 = new Student("Meera");

console.log(s1.name + ", " + s1.college + ", " + s1.marks);
console.log(s2.name + ", " + s2.college + ", " + s2.marks);

Output:

Kabir, City College, 85
Meera, City College, 0

Fields are created on each instance separately, so changing s1.marks doesn't affect s2. Fields make it easy to see at a glance what properties an object has.


Getters and Setters

Sometimes you want something that looks like a property but runs code when it's read or changed. That's what get and set do.

class Product {
    constructor(name, price) {
        this.name = name;
        this.price = price; // this calls the setter below
    }

    get price() {
        return this._price;
    }

    set price(value) {
        if (value < 0) {
            console.log("Price cannot be negative");
            return;
        }
        this._price = value;
    }

    get priceWithGst() {
        return this._price * 1.18;
    }
}

const phone = new Product("Phone", 20000);

console.log(phone.price);        // getter, no ()
console.log(phone.priceWithGst); // computed getter

phone.price = -500;              // setter rejects it
console.log(phone.price);

Output:

20000
23600
Price cannot be negative
20000

Key points:

  • Getters and setters are used without parentheses: phone.price, not phone.price().

  • The real value is stored in a different property (_price). If the setter wrote to this.price, it would call itself forever and crash with a "Maximum call stack size exceeded" error.

  • The underscore in _price is only a convention meaning "please don't touch". It is still publicly accessible. For real privacy, use private fields (below).

  • A getter without a setter (like priceWithGst) is read-only.


Static Properties and Methods

Normally, properties and methods belong to instances. A static member belongs to the class itself. You use it through the class name, not through an object.

class Student {
    static count = 0;

    constructor(name, marks) {
        this.name = name;
        this.marks = marks;
        Student.count++; // shared counter on the class
    }

    static compareMarks(a, b) {
        return b.marks - a.marks;
    }
}

const s1 = new Student("Kabir", 72);
const s2 = new Student("Meera", 91);

console.log(Student.count);
console.log(Student.compareMarks(s1, s2));
console.log(s1.compareMarks);

Output:

2
19
undefined

Static members are useful for things that relate to the class as a whole: counters, helper functions, and "factory" methods like Student.fromString("Kabir,72"). You've already used built-in static methods such as Math.max(), Object.keys() and Array.isArray().

s1.compareMarks is undefined because static members are not available on instances.


Private Fields and Methods

Prefix a field or method name with # to make it truly private. It can only be used by code inside the class body. (Private members are standard since ES2022 and supported in all modern browsers and Node.js.)

class BankAccount {
    #balance = 0; // private field

    constructor(owner, amount) {
        this.owner = owner;
        this.deposit(amount);
    }

    deposit(amount) {
        if (amount <= 0) {
            console.log("Invalid amount");
            return;
        }
        this.#balance += amount;
        this.#log("Deposited ₹" + amount);
    }

    withdraw(amount) {
        if (amount > this.#balance) {
            this.#log("Failed to withdraw ₹" + amount);
            return;
        }
        this.#balance -= amount;
        this.#log("Withdrew ₹" + amount);
    }

    get balance() {
        return this.#balance; // read-only from outside
    }

    #log(message) { // private method
        console.log(this.owner + ": " + message);
    }
}

const account = new BankAccount("Aman", 1000);
account.withdraw(5000);
account.withdraw(400);

console.log(account.balance);

account.balance = 1000000; // no setter → ignored
console.log(account.balance);

Output:

Aman: Deposited ₹1000
Aman: Failed to withdraw ₹5000
Aman: Withdrew ₹400
600
600

Trying to read account.#balance from outside the class isn't just blocked at runtime. It is a syntax error, so the whole script refuses to run:

SyntaxError: Private field '#balance' must be declared in an enclosing class

Compare this with the closure-based bank account from the Closures chapter: private fields give the same protection with class syntax.

(One note: assigning account.balance = 1000000 to a getter-only property is silently ignored in normal scripts, but throws a TypeError in strict mode, for example inside a class or module.)


Inheritance with extends

Often one kind of object is a more specific version of another. A manager is an employee, with some extra responsibilities. Instead of copying all the employee code, we can inherit it using extends.

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

    describe() {
        return this.name + " earns ₹" + this.salary;
    }

    work() {
        return this.name + " is writing code";
    }
}

class Manager extends Employee {
    constructor(name, salary, teamSize) {
        super(name, salary); // run Employee's constructor first
        this.teamSize = teamSize;
    }

    // override: replace the parent's version
    work() {
        return this.name + " is managing " + this.teamSize + " people";
    }

    // extend: reuse the parent's version and add to it
    describe() {
        return super.describe() + " and leads a team";
    }
}

const dev = new Employee("Riya", 80000);
const boss = new Manager("Arjun", 150000, 8);

console.log(dev.work());
console.log(boss.work());
console.log(dev.describe());
console.log(boss.describe());

console.log(boss instanceof Manager);
console.log(boss instanceof Employee);
console.log(dev instanceof Manager);

Output:

Riya is writing code
Arjun is managing 8 people
Riya earns ₹80000
Arjun earns ₹150000 and leads a team
true
true
false

The important pieces:

Syntax

Meaning

class Manager extends Employee

Manager (child/subclass) inherits from Employee (parent/superclass)

super(name, salary)

Calls the parent's constructor

super.describe()

Calls the parent's version of a method

Method with the same name

Overrides the parent's method

obj instanceof Class

true if obj was made by Class or any class that extends it

Call super() Before Using this

In a child class constructor, you must call super() before touching this. The parent is responsible for creating the object, so this doesn't exist yet until super() runs:

class Manager extends Employee {
    constructor(name, salary, teamSize) {
        this.teamSize = teamSize; // ❌ too early
        super(name, salary);
    }
}

new Manager("Arjun", 150000, 8);

Result:

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

If a child class has no constructor of its own, JavaScript automatically creates one that passes all arguments to super(...).


Classes Are Special Functions

A class is really a special kind of function, but with stricter rules:

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

console.log(typeof Student);

// try...catch catches the error so we can print it and keep going (covered in the Error Handling chapter)
try {
    Student("Kabir"); // forgot new
} catch (error) {
    console.log(error.name + ": " + error.message);
}

Output:

function
TypeError: Class constructor Student cannot be invoked without 'new'
  • Must use new. Calling a class like a normal function throws a TypeError.

  • Not usable before its declaration. Like let, a class is hoisted but stays in the Temporal Dead Zone (see the Hoisting chapter).

  • Always strict mode. Code inside a class body runs in strict mode automatically.


Losing this in Class Methods

Everything from the this Keyword chapter applies to classes. And because class bodies are always strict, a detached method gets this = undefined:

class Timer {
    seconds = 0;

    tick() {
        this.seconds++;
        console.log("Seconds: " + this.seconds);
    }

    // arrow function field: this is fixed to the instance
    tickArrow = () => {
        this.seconds++;
        console.log("Seconds: " + this.seconds);
    };
}

const timer = new Timer();

function runCallback(callback) {
    callback(); // plain function call
}

try {
    runCallback(timer.tick);
} catch (error) {
    console.log(error.message);
}

runCallback(timer.tick.bind(timer)); // fix 1: bind
runCallback(timer.tickArrow);        // fix 2: arrow function field
runCallback(() => timer.tick());     // fix 3: wrap in an arrow

Output:

Cannot read properties of undefined (reading 'seconds')
Seconds: 1
Seconds: 2
Seconds: 3

An arrow function stored in a class field captures this from the constructor, which is the instance. This pattern is very common in React class components and event handlers. The trade-off: each instance gets its own copy of an arrow field (it isn't shared like a normal method), so use it only where you really need it.


A Practical Example

Let's model shapes. Every shape has a name and can describe itself, but each calculates its area differently:

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

    area() {
        return 0;
    }

    describe() {
        return this.name + " with area " + this.area().toFixed(2);
    }
}

class Circle extends Shape {
    constructor(radius) {
        super("Circle");
        this.radius = radius;
    }

    area() {
        return Math.PI * this.radius ** 2;
    }
}

class Rectangle extends Shape {
    constructor(width, height) {
        super("Rectangle");
        this.width = width;
        this.height = height;
    }

    area() {
        return this.width * this.height;
    }
}

const shapes = [new Circle(3), new Rectangle(4, 5), new Circle(1)];

for (const shape of shapes) {
    console.log(shape.describe());
}

Output:

Circle with area 28.27
Rectangle with area 20.00
Circle with area 3.14

Notice that describe() is written only once in Shape, yet it calls the correct area() for each shape. That's because this.area() uses the actual object's method. This idea, where the same call behaves differently depending on the object, is called polymorphism, one of the four pillars of object-oriented programming (along with encapsulation, inheritance and abstraction).


Class vs Object Literal vs Factory Function

Approach

Best for

Privacy

Object literal { }

A single, one-off object (config, settings)

None

Factory function (returns an object)

Many objects, with privacy through closures

Closures

Class

Many objects of the same type, inheritance, shared methods

#private fields

None of these is "the only right way". Use a class when you'll create many similar objects or need inheritance.


Common Mistakes

  • Forgetting new. Student("Kabir") throws a TypeError.

  • Using this before super() in a child constructor.

  • Adding commas between methods like in an object literal. Class bodies don't use commas.

  • Writing this.price = value inside the price setter, causing infinite recursion.

  • Calling a static method on an instance (s1.compareMarks()) or an instance method on the class.

  • Passing a method as a callback and losing this. Use bind(), an arrow field, or an arrow wrapper.


Interview Tips

  • "Are JavaScript classes like Java classes?" The syntax is similar, but JavaScript classes are mostly syntactic sugar over prototypes. Methods live on the class's prototype object, and extends links prototypes together. (Next chapter.)

  • "How do you make a property private?" Use #field syntax (true privacy), or closures. An underscore _field is only a naming convention.

  • "What does super do?" super(...) calls the parent constructor; super.method() calls the parent's version of a method.

  • "What's the difference between a static and an instance method?" A static method is called on the class (Student.compare()) and has no specific instance; an instance method is called on an object (s1.introduce()).

Practice: create a Vehicle class with brand and a describe() method, then Car and Bike subclasses that override describe() and use super.describe(). Add a static counter of how many vehicles were created.

Conclusion

A class is a blueprint for creating many objects with the same structure and behaviour.

  • constructor() sets up each new instance; create instances with new.

  • Methods are shared by all instances; fields are created per instance.

  • get/set create computed or validated properties.

  • static members belong to the class itself.

  • #private fields and methods can only be used inside the class.

  • extends and super let one class inherit from and build on another.

In the next chapter, we'll look under the hood at prototypes, the mechanism that makes classes and inheritance work in JavaScript.