JavaScript · Advanced

Classes

Classes are blueprints for creating many similar objects. They package data and behaviour together in a clean, readable way.

Intermediate 5 min Lesson 39 of 49 Runnable examples
Before you start:Object Methods
0/49 in JavaScript
On this page · 5 min · Intermediate

Learning objectives#

  • Define classes with constructors and methods
  • Use getters, setters and private #fields
  • Add static properties
  • Extend classes with extends and super

Explanation#

class Product { constructor(name, price) { … } } defines a blueprint; new Product('Book', 500) creates an object from it.

Methods are shared by every instance. get and set let properties run code when read or written.

Fields starting with # are private — only code inside the class can access them.

static members belong to the class itself (Product.count), not to instances. extends creates a subclass; super calls the parent.

Code example: Products and digital products#

JavaScriptProducts and digital products Runnable
class Product {
  static count = 0;
  #discount = 0;


  constructor(name, price) {
    this.name = name;
    this.price = price;
    Product.count++;
  }
  set discount(pct) {
    if (pct < 0 || pct > 90) throw new RangeError('Discount must be 0–90%');
    this.#discount = pct;
  }
  get finalPrice() {
    return this.price * (1 - this.#discount / 100);
  }
  toString() {
    return `${this.name}: ₹${this.finalPrice}`;
  }
}


class DigitalProduct extends Product {
  constructor(name, price, sizeMb) {
    super(name, price);
    this.sizeMb = sizeMb;
  }
  toString() {
    return `${super.toString()} (${this.sizeMb} MB download)`;
  }
}


const book = new Product('Book', 500);
book.discount = 10;
const course = new DigitalProduct('Video course', 1200, 850);


console.log(String(book));
console.log(String(course));
console.log(Product.count, course instanceof Product);
Expected output
Book: ₹450
Video course: ₹1200 (850 MB download)
2 true
Opens this example in the full playground

Step-by-step explanation#

  1. The constructor sets up each product and increases the static counter.
  2. The discount setter validates the value before saving it in the private #discount field.
  3. finalPrice is a getter, so it is read like a property: book.finalPrice.
  4. DigitalProduct extends Product, calls super(...) and reuses super.toString().
  5. Two products were created, and a DigitalProduct is also a Product.

Real-world use case#

Models such as User, Order and ShoppingCart, custom errors (class NotFoundError extends Error), and Angular components and services are all classes.

Common mistakes#

Forgetting new

Calling Product('x', 1) without new throws a TypeError.

Using this before super()

In a subclass constructor, call super(...) first.

Best practices#

  • Keep classes small and focused
  • Use private #fields for internal state
  • Validate in setters or constructors
  • Prefer composition over deep inheritance

Remember this#

class = blueprint; new = build one.

# = private. static = belongs to the class, not each object.

extends + super() = “like my parent, plus extras”.

Practice exercise#

Your task: Create a BankAccount class with a private #balance, deposit(amount), withdraw(amount) that refuses overdrafts, and a balance getter.

Show solution
JavaScript Runnable
class BankAccount {
  #balance = 0;
  deposit(a) { this.#balance += a; }
  withdraw(a) { if (a > this.#balance) throw new Error('Insufficient funds'); this.#balance -= a; }
  get balance() { return this.#balance; }
}
const acc = new BankAccount();
acc.deposit(500); acc.withdraw(200);
console.log(acc.balance); // 300
Opens this example in the full playground

Mini quiz#

Classes quizMultiple choice Question 1 of 1

Where can a #private field be read?

Score so far: 0/0

Want more? Practise all JavaScript MCQs · JavaScript interview questions

My notes#

Saved in this browser.

Progress is saved in this browser. Sign in to sync.