Classes

Updated · 8 min read
hardES2026javascriptclassesoopconstructor

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; the constructor runs 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 without new throws.
  • Classes aren't hoisted like function declarations: define them before use.

Defining a Class

Syntax

syntax.js
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.js▶ Try it
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);
Output
Navika owes $150
Advitha owes $120
false

Explanation: 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.

PartWhere it livesCreated
Fields (payments = [])On each instanceOnce per new, before the constructor body
Properties set in the constructor (this.owner)On each instanceDuring the constructor
Methods and gettersOn Account.prototypeOnce, when the class is defined

Classes Are Functions Underneath

A class declaration creates a constructor function and fills in its prototype:

underneath.js▶ Try it
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);
Output
function
true
true false
true
true

This is exactly what the constructor functions lesson built by hand. The class syntax is clearer and adds safety:

Constructor functionClass
Called without newRuns with the wrong this (bug)Throws TypeError
Strict modeOnly if you add "use strict"Always
MethodsAdded to Fn.prototype by handWritten in the class body
Methods enumerable in for...inYesNo
HoistedYes (declarations)No (temporal dead zone)
Private members, static, extends, superWorkaroundsBuilt in
no-new.js▶ Try it
class Account {}
try {
  Account();
} catch (err) {
  console.log(err.name + ": " + err.message);
}
Output
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:

constructor.js▶ Try it
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);
  }
}
Output
{ 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:

fields.js▶ Try it
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);
Output
{ 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:

expression.js▶ Try it
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);
Output
Receipt #42
Receipt #43 2026-01-05T10:00:00Z

The 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:

JavaJavaScript
What a class isA compile-time typeA function object created at run time
MethodsBelong to the classLive on a prototype object; can be added or changed later
thisAlways the instanceDepends on how a method is called (can be lost)
OverloadingSeveral methods with the same nameNot supported; one method, check the arguments
Privateprivate keyword#name fields and methods
Interfaces, abstract classesBuilt inNot built in (TypeScript adds interfaces)
Multiple inheritanceInterfacesMixins
Fields without declarationNot allowedAny 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:

student.js▶ Try it
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);
}
Output
Navika (grade 9): $100 due
Only $100 is due

Common 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
counter.js▶ Try it
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()));
Output
Count: 3
Count: 0

Quick check: Classes

3 questions
1Where do class methods live?
2What is typeof a class?
3What happens when you call a class without new?

Key Takeaways

PartSyntax
Declareclass Account { ... }
Constructorconstructor(owner) { this.owner = owner; }
Fieldpayments = [];
Methoddescribe() { ... }
Getterget balance() { ... }
Instancenew Account("Navika")

Was this tutorial helpful?

Lesson 97 of 139