SyntaxPilot
Courses/JavaScript/Lesson 16

JavaScript · Lesson 16 of 40 · 13 min

Classes and objects

queued

These are the notes for JavaScript episode 16. You'll see why objects typed by hand drift apart (a typo here, a missing method there), fix it first with a factory function, and then invent the class: one blueprint with a constructor, built with new, whose methods are shared by every object. Then you'll lock data inside with private fields (#balance) and a getter, build a child class with extends and super, and keep class-wide data in static properties. Every example runs as-is in the SyntaxPilot compiler (language: JavaScript, Node.js), and every output and error below is real Node.js 24 output.

Builds on: objects and methods (episode 8), functions (9), errors and throw (13), and the quiz game (15).

The real-life idea: the school admission form

A school office designs one blank admission form: name, class, roll number, parent's phone. Five hundred students fill in copies. Every copy has the same boxes; only the values change.

Now imagine there's no printed form and every parent draws one by hand. One forgets the phone box, another misspells "roll number". The office can't process them. That is exactly what happens when we type objects by hand.

School JavaScript
The blank form design a class (the blueprint)
The clerk filling in one new copy new running the constructor
One filled form an object, also called an instance
One rule book kept at the office, shared by all forms methods, stored once and shared

Attempt 1: objects typed by hand

const q1 = {
  text: "Capital of India?", answer: "B",
  check(given) { return given.trim().toUpperCase() === this.answer; },
};
const q2 = {
  text: "2 + 2 * 2 = ?", answer: "A",
  check(given) { return given.trim().toUpperCase() === this.anwser; },
};
const q3 = {
  text: "Chai is made from?", answer: "C",
};
console.log(q1.check("b"));
console.log(q2.check("A"));
console.log(q3.check("C"));
true
false
/tmp/.../main.js:14
console.log(q3.check("C"));
               ^

TypeError: q3.check is not a function
  • q2 says false for a right answer: line 7 has a typo, this.anwser. A property that doesn't exist is undefined, and nothing equals undefined. No error, just a wrong answer.
  • q3 has no check at all, so calling it crashes.

Why it failed: every object is written by hand, so nothing guarantees they have the same shape. Three objects are manageable; three hundred will have broken ones.

Attempt 2: a factory function

A factory function is a normal function that builds and returns a new object. The shape is written once.

function makeQuestion(text, answer) {
  return {
    text,
    answer,
    check(given) { return given.trim().toUpperCase() === this.answer; },
  };
}
const q1 = makeQuestion("Capital of India?", "B");
const q2 = makeQuestion("2 + 2 * 2 = ?", "A");
console.log(q1.check("b"), q2.check("C"));
console.log(q1.check === q2.check);
true false
false
  • { text, answer } is the shorthand property syntax from episode 8: { text: text, answer: answer }.
  • Every question now has the same shape, and the typo can't happen.
  • But q1.check === q2.check is false: each call runs the object literal again, creating a new copy of check. 1,000 questions = 1,000 identical functions in memory. Like printing the whole rule book inside every admission form.

The fix: a class

class Question {
  constructor(text, answer) {
    this.text = text;
    this.answer = answer;
  }
  check(given) {
    return given.trim().toUpperCase() === this.answer;
  }
}
const q1 = new Question("Capital of India?", "B");
const q2 = new Question("2 + 2 * 2 = ?", "A");
console.log(q1);
console.log(q1.check("b"), q2.check("C"));
console.log(q1.check === q2.check);
console.log(q1 instanceof Question, typeof Question);
Question { text: 'Capital of India?', answer: 'B' }
true false
true
true function

How it works, step by step:

  1. class Question { ... } declares the blueprint. Class names start with a capital letter by convention.
  2. new Question("Capital of India?", "B") creates a fresh empty object and runs the constructor with those arguments.
  3. Inside the constructor, this is the new object being built. this.text = text stores the value on it.
  4. Methods like check are written in the class body: no function keyword, no commas between them. They are not copied into each object; every instance shares one function (q1.check === q2.check is true). That's why check doesn't appear when you print q1.
  5. instanceof tells you whether an object was built from a class.
  6. typeof Question is "function": a class is a special kind of function under the hood (episode 17 explains how).

Two classic mistakes

Forgetting new:

const q1 = Question("Capital of India?", "B");
TypeError: Class constructor Question cannot be invoked without 'new'

Without new there's no fresh object for this to point to, so JavaScript refuses.

Forgetting this. in the constructor:

class Question {
  constructor(text, answer) {
    text = text;
    answer = answer;
  }
  check(given) {
    return given.trim().toUpperCase() === this.answer;
  }
}
const q1 = new Question("Capital of India?", "B");
console.log(q1, q1.check("B"));
Question {} false

No error at all. text = text assigns the parameter to itself; nothing is stored on the object. To keep a value on the object, write this..

Private fields and getters: a wallet nobody can edit

A wallet app holds Asha's balance. With a normal property, any code can overwrite it:

class Wallet {
  constructor(owner, balance) {
    this.owner = owner;
    this.balance = balance;
  }
  pay(amount) {
    this.balance -= amount;
  }
}
const w = new Wallet("Asha", 500);
w.pay(120);
w.balance = -10000;
console.log(w);
Wallet { owner: 'Asha', balance: -10000 }

The fix is a private field: a name starting with #, declared in the class body. Only code inside the class can read or write it. A getter (get balance()) looks like a property from outside but runs a function; here it only reads.

class Wallet {
  #balance = 0;
  constructor(owner, balance) {
    this.owner = owner;
    this.#balance = balance;
  }
  pay(amount) {
    if (amount > this.#balance) throw new Error(`Not enough money: balance is ${this.#balance}`);
    this.#balance -= amount;
  }
  get balance() {
    return this.#balance;
  }
}
const w = new Wallet("Asha", 500);
w.pay(120);
console.log(w.balance);
w.balance = -10000;
console.log(w.balance, w);
try {
  w.pay(1000);
} catch (err) {
  console.log(err.message);
}
380
380 Wallet { owner: 'Asha' }
Not enough money: balance is 380
  • Writing w.balance = -10000 is ignored: there's a getter but no setter. (In strict code, such as inside a class or an ES module, it throws TypeError: Cannot set property balance of #<Wallet> which has only a getter.)
  • Printing w doesn't show #balance: it's hidden.
  • pay is the only way to change the balance, and it enforces the rule.

Reading a private field from outside is caught before the program even starts:

console.log(w.#balance);
SyntaxError: Private field '#balance' must be declared in an enclosing class

Keeping data inside an object and allowing changes only through its methods is called encapsulation.

A setter is the writing twin of a getter, if you ever need one:

set balance(value) {
  if (value < 0) throw new Error("balance can't be negative");
  this.#balance = value;
}

extends and super: a class built on a class

A student wallet does everything a wallet does, plus a limit per payment. Copy-pasting the whole class would bring back the copy-paste bugs, so we extend it:

class StudentWallet extends Wallet {
  constructor(owner, balance, limit) {
    super(owner, balance);
    this.limit = limit;
  }
  pay(amount) {
    if (amount > this.limit) throw new Error(`Limit is ${this.limit} per payment`);
    super.pay(amount);
  }
}
const s = new StudentWallet("Ravi", 300, 100);
s.pay(80);
console.log(s.balance, s.owner);
try { s.pay(150); } catch (err) { console.log(err.message); }
console.log(s instanceof StudentWallet, s instanceof Wallet);

(with the Wallet class from above in the same file)

220 Ravi
Limit is 100 per payment
true true
  • extends Wallet: StudentWallet (the child or derived class) starts with everything Wallet (the parent or base class) has.
  • super(owner, balance) runs the parent's constructor, so owner and #balance are set up.
  • super.pay(amount) calls the parent's version of pay from inside the child's version. The child overrides pay but still reuses the balance check.
  • The getter balance and owner come from Wallet for free.
  • A StudentWallet is an instance of both classes.

Forget super(...) and the constructor fails:

ReferenceError: Must call super constructor in derived class before accessing 'this' or returning from derived constructor

In a child class, this doesn't exist until the parent has built it, so call super() first.

static: data that belongs to the class

class Question {
  static count = 0;
  constructor(text) {
    this.text = text;
    Question.count++;
  }
}
new Question("Capital of India?");
new Question("2 + 2 * 2 = ?");
const q3 = new Question("Chai is made from?");
console.log(Question.count, q3.count);
3 undefined

A static property (or method) lives on the class itself, not on the instances, like the total admissions written on the office board rather than on one form. Math.round and Number.isInteger are static methods you already know.

Common mistakes (and what really happens)

You wrote What happens Why Fix
const q = Question("Hi", "B") TypeError: Class constructor Question cannot be invoked without 'new' a class must be called with new new Question(...)
constructor(text) { text = text; } (no error) Question {} nothing stored on the object this.text = text
this.anwser (typo) (no error) undefined, so the check is false missing properties are undefined one class, one spelling
q3.check("C") on a hand-typed object with no check TypeError: q3.check is not a function the method was never written build objects from a class
console.log(w.#balance) outside the class SyntaxError: Private field '#balance' must be declared in an enclosing class private fields are inside-only a getter or a method
child constructor without super() ReferenceError: Must call super constructor in derived class before accessing 'this' ... the parent hasn't built this yet call super(...) first
q3.count for a static property (no error) undefined static lives on the class Question.count
commas between methods: check() {}, hint() {} SyntaxError: Unexpected token ',' a class body is not an object literal no commas between methods

Mini project: a bank account

class BankAccount {
  static count = 0;
  #balance = 0;
  constructor(owner) {
    this.owner = owner;
    BankAccount.count++;
  }
  deposit(amount) {
    if (amount <= 0) throw new Error("Deposit must be positive");
    this.#balance += amount;
    return this;
  }
  withdraw(amount) {
    if (amount > this.#balance) throw new Error(`Only ₹${this.#balance} available`);
    this.#balance -= amount;
    return this;
  }
  get balance() {
    return this.#balance;
  }
}
class SavingsAccount extends BankAccount {
  constructor(owner, rate) {
    super(owner);
    this.rate = rate;
  }
  addInterest() {
    return this.deposit(Math.round(this.balance * this.rate / 100));
  }
}
const a = new SavingsAccount("Meena", 4);
a.deposit(1000).addInterest();
console.log(a.owner, a.balance);
try { a.withdraw(5000); } catch (err) { console.log(err.message); }
console.log(BankAccount.count);
Meena 1040
Only ₹1040 available
1

Returning this from a method lets you chain calls: a.deposit(1000).addInterest().

Practice

  1. Rewrite the episode 15 quiz with a Question class that has text, options, answer and a check(given) method.
  2. Add a TrueFalseQuestion extends Question whose options are always ["True", "False"].
  3. Give Question a static method fromLine(line) that builds a question from "Capital of India?|Mumbai,Delhi,Pune|B".
Solutions
class Question {
  constructor(text, options, answer) {
    this.text = text;
    this.options = options;
    this.answer = answer;
  }
  check(given) {
    return (given || "").trim().toUpperCase() === this.answer;
  }
  static fromLine(line) {
    const [text, opts, answer] = line.split("|");
    return new Question(text, opts.split(","), answer);
  }
}
class TrueFalseQuestion extends Question {
  constructor(text, answer) {
    super(text, ["True", "False"], answer);
  }
}
const qs = [
  Question.fromLine("Capital of India?|Mumbai,Delhi,Pune|B"),
  new TrueFalseQuestion("JavaScript runs in browsers", "A"),
];
for (const q of qs) console.log(q.text, q.options, q.check("b"));
Capital of India? [ 'Mumbai', 'Delhi', 'Pune' ] true
JavaScript runs in browsers [ 'True', 'False' ] false

fromLine is static because it doesn't belong to one question: it makes questions.

Quick quiz

What does this print?

class Counter {
  #n = 0;
  add() { this.#n++; return this; }
  get value() { return this.#n; }
}
const c = new Counter();
console.log(c.add().add().value, c.n);
  • A. 2 undefined
  • B. 2 2
  • C. 0 undefined
  • D. SyntaxError
Answer

A. add() returns this, so the calls chain and #n becomes 2. c.n is a different, public name that was never set: undefined. (Reading c.#n outside the class would be a SyntaxError, but c.n is legal.)

Interview questions

  • What is a class in JavaScript? What does new do, step by step?
  • What is the difference between a factory function and a class? Which shares methods?
  • What is this inside a constructor?
  • What are private fields (#x)? How are they different from the old _x naming convention?
  • What is a getter? A setter? When would you use them?
  • What do extends and super do? Why must super() come before this in a child constructor?
  • What is method overriding?
  • What is a static method? Give a built-in example.
  • What does instanceof check?
  • What is encapsulation?

Glossary

Term Meaning Example
Object a value holding named properties { text: "Hi", answer: "B" }
Property a named value inside an object q1.text
Method a function stored as a property, called on an object q1.check("b")
Factory function a normal function that builds and returns a new object makeQuestion(text, answer)
Class a blueprint for making objects of the same shape class Question { }
Instance one object made from a class q1 is an instance of Question
new creates a new object and runs the class's constructor new Question("Hi", "B")
Constructor the special method that fills in a new object constructor(text, answer) { ... }
this (in a class) the object the code is working on this.text = text
instanceof checks if an object was built from a class q1 instanceof Question → true
Private field a property only code inside the class can use; starts with # #balance
Getter a method that is read like a property get balance() { ... } → w.balance
Setter a method that runs when a property is assigned set balance(v) { ... }
Encapsulation hiding data inside an object, changed only through its methods #balance + pay()
extends makes a class that starts from another class class StudentWallet extends Wallet
Parent / base class the class being extended Wallet
Child / derived class the class that extends another StudentWallet
super(...) calls the parent's constructor super(owner, balance)
super.method() calls the parent's version of a method super.pay(amount)
Override a child redefines a parent's method StudentWallet's pay
static belongs to the class itself, not to instances Question.count
Method chaining calling methods one after another because each returns this a.deposit(100).addInterest()

Summary

  • Hand-typed objects drift: typos and missing methods sneak in silently.
  • A factory function fixes the shape but copies every method into every object.
  • A class is a blueprint: new runs the constructor, this is the new object, and methods are shared by every instance.
  • Private fields (#x) and getters protect data (encapsulation).
  • extends builds a child class; super() runs the parent's constructor (first!), super.method() reuses the parent's method.
  • static data and methods belong to the class.

Next episode: prototypes and this. check isn't stored in q1, yet q1.check works, so where does it live? And why does this sometimes become undefined?