Classes
Classes are blueprints for creating many similar objects. They package data and behaviour together in a clean, readable way.
On this page · 5 min · Intermediate
On this page
- Learning objectives
- Explanation
- Code example
- Step by step
- Real-world use
- Common mistakes
- Best practices
- Remember this
- Practice exercise
- Mini quiz
- Related topics
- My notes
- Reading time
- 5 min
- Difficulty
- Intermediate
- Updated
- Oct 27, 2026
Related tutorials
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#
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);
Book: ₹450 Video course: ₹1200 (850 MB download) 2 true
Step-by-step explanation#
- The constructor sets up each product and increases the static counter.
- The discount setter validates the value before saving it in the private #discount field.
- finalPrice is a getter, so it is read like a property: book.finalPrice.
- DigitalProduct extends Product, calls super(...) and reuses super.toString().
- 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#
Calling Product('x', 1) without new throws a TypeError.
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
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
Mini quiz#
Where can a #private field be read?
Want more? Practise all JavaScript MCQs · JavaScript interview questions
My notes#
Saved in this browser.