Classes
A class is a blueprint for creating objects that share the same structure and behavior. You define the data each object starts with in a constructor (and in fields), and the operations as methods; then new ClassName(...) creates instances. JavaScript classes, introduced in ES2015, are mostly a cleaner syntax over the prototype system from the previous lesson: methods live on the class's prototype and are shared by every instance. They add real improvements too: they must be called with new, run in strict mode, and support inheritance, private members and static members cleanly.
In One Minute
class Account { constructor(owner) { this.owner = owner; } describe() { ... } }new Account("Navika")creates an instance; theconstructorruns to set it up.- Methods are shared through
Account.prototype; fields (balance = 0;) are created on each instance. - A class is a function underneath (
typeof Account === "function"), but calling it withoutnewthrows. - Classes aren't hoisted like function declarations: define them before use.
Defining a Class
Syntax
class ClassName {
field = initialValue; // instance field (optional)
constructor(param1, param2) { // runs on new ClassName(...)
this.property = param1;
}
method() { // shared by all instances
return this.property;
}
}
const instance = new ClassName(arg1, arg2);Example
class Account {
payments = [];
constructor(owner, fee) {
this.owner = owner;
this.fee = fee;
}
pay(amount) {
this.payments.push(amount);
return this;
}
get balance() {
return this.fee - this.payments.reduce((sum, p) => sum + p, 0);
}
describe() {
return `${this.owner} owes $${this.balance}`;
}
}
const navika = new Account("Navika", 450);
navika.pay(200).pay(100);
console.log(navika.describe());
const advitha = new Account("Advitha", 120);
console.log(advitha.describe());
console.log(navika.payments === advitha.payments);Navika owes $150
Advitha owes $120
falseExplanation: new Account("Navika", 450) creates an object, initializes the payments field to a new empty array, then runs the constructor with this set to the new object. Each instance gets its own payments array. pay, describe and the balance getter are defined once and shared. pay returns this, which allows chaining.
| Part | Where it lives | Created |
|---|---|---|
Fields (payments = []) | On each instance | Once per new, before the constructor body |
Properties set in the constructor (this.owner) | On each instance | During the constructor |
| Methods and getters | On Account.prototype | Once, when the class is defined |
Classes Are Functions Underneath
A class declaration creates a constructor function and fills in its prototype:
class Payment {
constructor(amount) {
this.amount = amount;
}
label() {
return `$${this.amount}`;
}
}
const p = new Payment(120);
console.log(typeof Payment);
console.log(Object.getPrototypeOf(p) === Payment.prototype);
console.log(Object.hasOwn(p, "amount"), Object.hasOwn(p, "label"));
console.log(Object.hasOwn(Payment.prototype, "label"));
console.log(Payment.prototype.constructor === Payment);function
true
true false
true
trueThis is exactly what the constructor functions lesson built by hand. The class syntax is clearer and adds safety:
| Constructor function | Class | |
|---|---|---|
Called without new | Runs with the wrong this (bug) | Throws TypeError |
| Strict mode | Only if you add "use strict" | Always |
| Methods | Added to Fn.prototype by hand | Written in the class body |
Methods enumerable in for...in | Yes | No |
| Hoisted | Yes (declarations) | No (temporal dead zone) |
Private members, static, extends, super | Workarounds | Built in |
class Account {}
try {
Account();
} catch (err) {
console.log(err.name + ": " + err.message);
}TypeError: Class constructor Account cannot be invoked without 'new'The Constructor
The constructor method runs when an instance is created. A class has at most one; if you leave it out, an empty one is used. Validation belongs here, so an invalid object can never exist:
class Payment {
constructor(name, amount) {
if (typeof name !== "string" || name.trim() === "") throw new TypeError("name is required");
if (!Number.isFinite(amount) || amount <= 0) throw new RangeError(`invalid amount: ${amount}`);
this.name = name.trim();
this.amount = amount;
this.createdAt = "2026-01-05";
}
}
console.log(new Payment(" Srihitha ", 85));
for (const args of [["", 10], ["Navika", -5]]) {
try {
new Payment(...args);
} catch (err) {
console.log(err.name, err.message);
}
}{ name: 'Srihitha', amount: 85, createdAt: '2026-01-05' }
TypeError name is required
RangeError invalid amount: -5(This site's console prints instances as plain objects, without the class name; the browser console and Node.js show Payment { ... }.)
Fields
Class fields (ES2022) declare instance properties in the class body, with optional initial values. They make the shape of an instance visible at a glance:
class Settings {
currency = "USD";
pageSize = 25;
createdBy;
tags = [];
constructor(createdBy) {
this.createdBy = createdBy;
}
}
const a = new Settings("Navika");
const b = new Settings("Advitha");
a.tags.push("dark-mode");
console.log(a, b.tags);{ currency: 'USD', pageSize: 25, createdBy: 'Navika', tags: ['dark-mode'] } []Field initializers run for each instance, so tags = [] gives every object its own array. (Putting an array on the prototype instead would share it between all instances, a classic bug.) Fields without a value start as undefined.
Class Expressions
Like functions, classes can be expressions: assigned to variables, passed to functions, or created by functions:
const Receipt = class {
constructor(id) { this.id = id; }
toString() { return `Receipt #${this.id}`; }
};
console.log(String(new Receipt(42)));
function withTimestamp(Base) {
return class extends Base {
stamp = "2026-01-05T10:00:00Z";
};
}
const StampedReceipt = withTimestamp(Receipt);
const r = new StampedReceipt(43);
console.log(String(r), r.stamp);Receipt #42
Receipt #43 2026-01-05T10:00:00ZThe second example is a mixin: a function that takes a class and returns a subclass with extra behavior. extends is covered in the next lesson.
JavaScript Classes vs Java Classes
If you know Java or C#, most of the syntax will feel familiar, with some important differences:
| Java | JavaScript | |
|---|---|---|
| What a class is | A compile-time type | A function object created at run time |
| Methods | Belong to the class | Live on a prototype object; can be added or changed later |
this | Always the instance | Depends on how a method is called (can be lost) |
| Overloading | Several methods with the same name | Not supported; one method, check the arguments |
| Private | private keyword | #name fields and methods |
| Interfaces, abstract classes | Built in | Not built in (TypeScript adds interfaces) |
| Multiple inheritance | Interfaces | Mixins |
| Fields without declaration | Not allowed | Any property can be added at any time |
In Practice
The Fee Tracker's Student class validates on creation, keeps its payments, and exposes a computed balance and a readable summary:
class Student {
payments = [];
constructor(name, grade, termFee) {
if (!Number.isInteger(grade) || grade < 1 || grade > 12) throw new RangeError(`bad grade ${grade}`);
this.name = name;
this.grade = grade;
this.termFee = termFee;
}
recordPayment(amount, date) {
if (amount > this.balance) throw new RangeError(`Only $${this.balance} is due`);
this.payments.push({ amount, date });
return this;
}
get balance() {
return this.termFee - this.payments.reduce((sum, p) => sum + p.amount, 0);
}
toString() {
return `${this.name} (grade ${this.grade}): $${this.balance} due`;
}
}
const navika = new Student("Navika", 9, 450);
navika.recordPayment(200, "2026-01-05").recordPayment(150, "2026-02-05");
console.log(String(navika));
try {
navika.recordPayment(500, "2026-03-05");
} catch (err) {
console.log(err.message);
}Navika (grade 9): $100 due
Only $100 is dueCommon Mistakes
Calling a class without new. It throws. Always new ClassName().
Forgetting this. inside methods. balance alone refers to a variable, not the property.
Passing methods as callbacks. setTimeout(student.recordPayment, ...) loses this. Use an arrow wrapper.
Using a class before its declaration. Classes are in the temporal dead zone until defined.
Practice
Challenge: Write a Counter class with a count field starting at 0, increment() and reset() methods that return this, and a toString() that returns "Count: n".
Show solution
class Counter {
count = 0;
increment() {
this.count++;
return this;
}
reset() {
this.count = 0;
return this;
}
toString() {
return `Count: ${this.count}`;
}
}
const c = new Counter();
console.log(String(c.increment().increment().increment()));
console.log(String(c.reset()));Count: 3
Count: 0Key Takeaways
| Part | Syntax |
|---|---|
| Declare | class Account { ... } |
| Constructor | constructor(owner) { this.owner = owner; } |
| Field | payments = []; |
| Method | describe() { ... } |
| Getter | get balance() { ... } |
| Instance | new Account("Navika") |
Was this tutorial helpful?