Classes are clean syntax for creating objects with shared behaviour — the same prototype mechanism from the last chapter, but readable. If you did the Python or React courses this will feel familiar; it's the standard way to model a domain in larger apps.
Defining a class
class Student {constructor(name, pkg = 0) { // runs on 'new'this.name = name;this.package = pkg;}raise(pct) {this.package *= 1 + pct / 100;}summary() {return `${this.name}: ₹${this.package} LPA`;}}const s = new Student("Aanya", 8);s.raise(25);s.summary(); // "Aanya: ₹10 LPA"
Inheritance
extends creates a subclass; super() calls the parent constructor and parent methods:
class Person {constructor(name) { this.name = name; }greet() { return `Hi, I'm ${this.name}`; }}class Mentor extends Person {constructor(name, company) {super(name); // call Person's constructorthis.company = company;}greet() {return `${super.greet()} from ${this.company}`;}}
Static & private members
class MathUtil {static PI = 3.14159;static square(n) { return n * n; } // call on the class, not an instance}MathUtil.square(5); // 25class Account {#balance = 0; // # = truly privatedeposit(n) { this.#balance += n; }get balance() { return this.#balance; }}
Getters & setters
get/set expose a method as if it were a property — the same idea as Python's @property — letting you compute or validate on access:
class Circle {constructor(r) { this.r = r; }get area() { return Math.PI * this.r ** 2; } // read like a propertyset radius(v) {if (v <= 0) throw new Error("radius must be positive");this.r = v;}}const c = new Circle(2);c.area; // 12.566… (no parentheses)c.radius = 5; // goes through the setter
Practice
Build a Programme class with a name, fee and a discounted-fee getter. Subclass it as Flagship that adds a mentor and overrides summary() with super. Add a static factory method that builds a default programme.
Key takeaways
- 01A class has a constructor (runs on new) and methods shared by all instances.
- 02extends + super() implement inheritance — call and override parent behaviour.
- 03static members belong to the class itself; #name fields are truly private.
- 04get/set expose methods as properties for computed or validated access.
- 05Classes are readable syntax over JavaScript's prototype mechanism.
