Lesson 23 of 28
In progress
Classes and private fields
Write classes with constructors and methods, extend them with super, and keep internal state private with # fields.
A class is a template for objects that share behaviour. JavaScript’s version is built on prototypes, but the class syntax is easier to read and covers most application code.
What you will learn
- Define a class with a constructor and methods.
- Use getters, static members and private fields.
- Extend a class with
extendsandsuper.
A class in practice
Editable. Runs in your browser.
constructor(label) {
this.label = label;
}
increment() {
this.#count += 1;
return this.#count;
}
get value() {
return this.#count;
}
}
const clicks = new Counter("Clicks");
clicks.increment();
clicks.increment();
console.log(clicks.label, clicks.value);
console.log(clicks.count);
Press Run to see the output.
#count is a private field: it is inaccessible outside the class, and clicks.count is simply undefined. That is real privacy, not a naming convention, and it makes the public surface of the class obvious.
Methods live on the prototype, so every instance shares them. Fields declared with = run per instance, before the constructor body.
Getters and setters
Editable. Runs in your browser.
constructor(celsius) {
this.#celsius = celsius;
}
get celsius() {
return this.#celsius;
}
set celsius(value) {
if (typeof value !== "number" || Number.isNaN(value)) {
throw new TypeError("Temperature must be a number");
}
this.#celsius = value;
}
get fahrenheit() {
return this.#celsius * 9 / 5 + 32;
}
}
const t = new Temperature(25);
console.log(t.fahrenheit);
t.celsius = 30;
console.log(t.celsius);
Press Run to see the output.
A getter computes a value on read; a setter validates on write. Validation in a setter is the class’s main advantage over a plain object: no caller can put it into an invalid state without an error.
Throwing from a setter is appropriate for programmer errors. For user input, validate before assigning and show a message instead.
Static members
Editable. Runs in your browser.
static convert(amount, currency) {
const rate = Money.#rates[currency];
if (!rate) throw new Error(`Unknown currency: ${currency}`);
return Math.round(amount * rate);
}
constructor(paise) {
this.paise = paise;
}
format() {
return `₹${(this.paise / 100).toFixed(2)}`;
}
}
console.log(Money.convert(10, "USD"));
console.log(new Money(1250).format());
Press Run to see the output.
Static members belong to the class, not an instance. They are right for helpers that do not depend on a particular object, such as a conversion table or a factory. A static method that only formats a value could be a plain function; use classes when the grouping earns its keep.
Inheritance
Editable. Runs in your browser.
describe() {
return `${this.owner}: ${this.balance}`;
}
}
class Savings extends Account {
constructor(owner, balance, rate = 0.04) {
super(owner, balance);
this.rate = rate;
}
describe() {
return `Savings — ${super.describe()}`;
}
}
const s = new Savings("Ana", 1000);
console.log(s.describe());
console.log(s instanceof Account);
Press Run to see the output.
super(...) runs the parent constructor and must be called before using this in the subclass constructor. super.method() calls the parent implementation, which is how you extend rather than replace behaviour.
Two levels are usually enough. When a hierarchy grows, composition — an object holding another object — is easier to change and test.
Changing state safely
A class is a good place to keep invariants, the rules that must always hold. If every method goes through the same validation, no caller can leave the object in an impossible state.
Editable. Runs in your browser.
add(name, price) {
if (!name || price < 0) throw new Error("Invalid item");
this.#items.push({ name, price });
return this;
}
get total() {
return this.#items.reduce((sum, item) => sum + item.price, 0);
}
}
const cart = new Cart().add("Pen", 20).add("Book", 120);
console.log(cart.total);
try {
cart.add("", 10);
} catch (error) {
console.log("Rejected:", error.message);
}
Press Run to see the output.
The array is private, so the only way to add an item is through add, which checks it. total is computed from the same data, so it cannot drift out of sync the way a stored total can.
Printing and serialising
toString() controls how an instance becomes text, and toJSON() controls what JSON.stringify stores. Both are worth defining when an object is logged or saved.
Editable. Runs in your browser.
toString() {
return `[${this.done ? "x" : " "}] ${this.title}`;
}
toJSON() {
return { title: this.title, done: this.done };
}
}
const task = new Task("Ship the lesson");
console.log(String(task));
console.log(JSON.stringify(task));
Press Run to see the output.
Without toJSON, stringify would include every enumerable field, including ones you consider internal. With it, the stored shape is explicit and can differ from the in-memory shape.
Classes or factories?
A class suits state with behaviour and validation, especially when several instances exist. A closure-based factory suits a single object with private state and no inheritance.
Editable. Runs in your browser.
const c = createCounter("Visits");
c.increment();
console.log(c.label ?? "no label", c.value);
Press Run to see the output.
Private fields are also skipped by Object.keys, JSON.stringify and spread, which keeps internal state out of logs and out of accidental copies. Expose what callers need through getters rather than reaching for the field itself.
Both are valid. Choose the one that reads better at the call site, and do not mix styles within one feature.
Using an arrow function for a class method does not create a prototype method; it creates a per-instance field. That costs memory per object and breaks super calls. Use the method shorthand methodName() {} in classes, and arrows only for callbacks passed to other functions.
Write a Playlist class with a private #songs array, an add(song) method, a length getter and a toString() method. Then create two playlists and show that their contents are independent.
Show solution
Editable. Runs in your browser.
constructor(name) {
this.name = name;
}
add(song) {
this.#songs.push(song);
return this;
}
get length() {
return this.#songs.length;
}
toString() {
return `${this.name} (${this.length})`;
}
}
const road = new Playlist("Road");
const study = new Playlist("Study");
road.add("Highway").add("Drives");
console.log(String(road), String(study));
Press Run to see the output.
The private array is created per instance, so the two playlists cannot share it. Returning this from add allows chaining without exposing the array.
Recap
#fieldsare genuinely private; getters and setters control access.- Static members belong to the class;
superextends a parent constructor or method. - Prefer shallow inheritance or composition, and use method shorthand rather than arrow fields.
Next, you will look at the tooling around real projects: npm, debugging and tests.
Do classes change how this works?
Can I add a method to a class later?
Progress is saved in this browser only. No account, no email.