Skip to content
LumenaryAcademy
Practice 60 min

Objects, prototypes and classes

Object literals, the prototype chain underneath everything, and the class syntax built on top of it.

Code tested · 4AI-draftedAwaiting review by a computer scientist
MotivationH

Everything is (nearly) an object

Apart from the seven primitive types, every value in JavaScript is an object: plain records like { name: "Kyoto" }, arrays, functions, dates, maps, errors, the DOM nodes of a web page. Even primitives borrow object behaviour when you call a method on them: "abc".toUpperCase() works because the engine looks the method up on String.prototype.

So understanding objects is understanding most of the language. They come in three layers, and this lesson goes through them in order. The first is object literals, the everyday tool for grouping data, which is also what JSON is based on. The second is prototypes, JavaScript's own mechanism for sharing behaviour, borrowed from the research language Self: an object can delegate to another object. The third is classes, added in 2015, which give prototypes a familiar syntax and, since 2022, add truly private fields. Professionals use all three, and knowing the middle layer is what makes the other two predictable.

Worked examplesH

Object literals

An object is a collection of properties, each a key (a string or a symbol) with a value. The literal syntax creates one directly:

javascript
// Objects: bags of named properties.
const field = "population";
const city = {
  name: "Kyoto",
  country: "Japan",
  [field]: 1_460_000,                      // computed key
  "founded in": 794,                       // keys that aren't identifiers need quotes
  location: { lat: 35.01, lon: 135.77 },
  describe() {                             // method shorthand
    return `${this.name}, ${this.country}`;
  },
};

console.log(city.name, city["founded in"], city[field]);
console.log(city.describe());

// Missing properties are undefined; optional chaining stops at null/undefined.
console.log(city.mayor);
console.log(city.mayor?.name, city.location?.lat);
console.log(city.mayor?.name ?? "no mayor on record");

// Adding, changing, removing, testing.
city.nickname = "City of Ten Thousand Shrines";
city.population += 1;
delete city.nickname;
console.log("nickname" in city, Object.hasOwn(city, "name"));

// Listing properties.
const scores = { Ama: 82, Bilal: 91, Chen: 77 };
console.log(Object.keys(scores), Object.values(scores));
for (const [person, score] of Object.entries(scores)) {
  if (score > 80) console.log(`${person} passed with ${score}`);
}
const curved = Object.fromEntries(
  Object.entries(scores).map(([person, score]) => [person, score + 5]),
);
console.log(curved);

// Objects are references: two names, one object.
const a = { n: 1 };
const b = a;
b.n = 2;
console.log(a.n, a === b, { n: 2 } === { n: 2 });
text
Kyoto 794 1460000
Kyoto, Japan
undefined
undefined 35.01
no mayor on record
false true
[ 'Ama', 'Bilal', 'Chen' ] [ 82, 91, 77 ]
Ama passed with 82
Bilal passed with 91
{ Ama: 87, Bilal: 96, Chen: 82 }
2 true false

The everyday toolkit:

  • Dot or brackets. city.name when the key is a fixed identifier; city[expression] when the key is computed or not a valid identifier. Inside a literal, [field]: value computes a key.
  • Missing means undefined, not an error. But reading a property of undefined throws, which is the most common runtime error in JavaScript. Optional chaining a?.b evaluates to undefined instead of throwing when a is null or undefined; it also works for calls (obj.method?.()) and brackets (obj?.[key]). Pair it with ?? for a default.
  • Listing. Object.keys, Object.values and Object.entries return arrays of an object's own enumerable properties, and Object.fromEntries turns [key, value] pairs back into an object. Together with array methods they are the idiomatic way to transform an object. (The [person, score] in the loop is destructuring, lesson six.)
  • Testing. Object.hasOwn(obj, key) asks whether the object itself has the property; key in obj also looks along the prototype chain.
  • References. A variable holds a reference to an object, so const b = a creates a second name for the same object, and === on objects compares identity, never contents: two separately created { n: 2 } are not equal.

Integer-like keys are listed first, in ascending numeric order, then string keys in insertion order. Do not rely on the order of keys to mean anything; if order matters, use an array or a Map (lesson six).

Getters and setters

A property can also be computed. get total() { ... } inside a literal or class defines a getter, run whenever the property is read; set total(value) { ... } defines a setter, run on assignment. You saw one in lesson four (visits.value). Use them for values derived from other state, and keep them cheap and free of surprises: a reader of order.total does not expect a network request.

IntuitionH

Prototypes: objects that delegate

Definition— prototype and prototype chain

Every object has an internal link to another object, or to null, called its prototype. When you read a property the object does not have itself, the engine looks in its prototype, then in the prototype's prototype, and so on until it finds the property or reaches null. This sequence of objects is the prototype chain. Writing a property always writes to the object itself, never to its prototypes.

javascript
// Prototypes: when a property is missing, the lookup continues in the prototype.
const animal = {
  describe() {
    return `${this.name} says ${this.sound}`;
  },
  sound: "...",
};

const dog = Object.create(animal);          // dog's prototype is animal
dog.name = "Rex";
dog.sound = "woof";

const fish = Object.create(animal);
fish.name = "Nemo";                         // no sound of its own

console.log(dog.describe());                // describe found on animal, this is dog
console.log(fish.describe());               // sound found on animal too
console.log(Object.hasOwn(dog, "describe"), "describe" in dog);
console.log(Object.getPrototypeOf(dog) === animal);
console.log(Object.getPrototypeOf(animal) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype));

// The chain is live: adding to the prototype affects every object that uses it.
animal.legs = 4;
console.log(dog.legs, fish.legs);

// Built-ins work the same way: arrays get their methods from Array.prototype.
const list = [3, 1, 2];
console.log(Object.getPrototypeOf(list) === Array.prototype, Object.hasOwn(list, "map"));

// Before classes: a constructor function and its .prototype object.
function Vector(x, y) {
  this.x = x;
  this.y = y;
}
Vector.prototype.length = function () {
  return Math.hypot(this.x, this.y);
};
const v = new Vector(3, 4);
console.log(v.length(), Object.getPrototypeOf(v) === Vector.prototype);
text
Rex says woof
Nemo says ...
false true
true
true
null
4 4
true false
5 true

Follow the lookups. dog.describe is not on dog, so the engine finds it on animal; it is called as dog.describe(), so this is dog (lesson four's rule), and this.sound finds "woof" on dog itself. For fish, this.sound is not found on fish and is found on animal. dog's own sound shadows the prototype's. The chain for dog is dog → animal → Object.prototype → null, and Object.prototype is where hasOwnProperty, toString and friends live.

This is how JavaScript shares behaviour without copying it: a million arrays share one map function on Array.prototype. And it is what the last part shows: before 2015, a "class" was a constructor function called with new, whose prototype property became the prototype of every object it created. new Vector(3, 4) creates an object whose prototype is Vector.prototype, runs Vector with this set to it, and returns it.

Analogy, not a formal construction

Prototypes work like asking a colleague. If you don't know the answer, you ask the person who trained you; if they don't know, they ask their trainer. Nobody memorises everything, nothing is copied, and when a trainer learns something new, everyone who relies on them knows it at once.

Never change the prototypes of built-in objects (Array.prototype.last = ...) in code that others will use. It affects every array in the program, and when the language later adds a method of the same name, your page breaks or the standard has to be bent around you. This has really happened: an array method planned for ES2016 had to be named includes rather than contains, because an old, popular library had already added an incompatible contains to built-in prototypes, and the standard name would have broken every site that used it.

DefinitionsH

Classes

Definition— class

A class declaration creates a constructor function together with a prototype object holding its methods, in one readable block. new ClassName(...) creates an instance whose prototype is ClassName.prototype and runs the constructor. extends links one class's prototype to another's, and super calls the parent's constructor or methods. Class bodies are always in strict mode.

javascript
// Classes: a clearer syntax for constructors and prototypes, plus truly private fields.
class Account {
  static #nextId = 1;                // private and static: shared by the class
  #balanceCents = 0;                 // private instance field: invisible outside the class
  owner;                             // public instance field

  constructor(owner, openingCents = 0) {
    this.id = Account.#nextId++;
    this.owner = owner;
    this.deposit(openingCents);
  }

  deposit(cents) {
    if (!Number.isInteger(cents) || cents < 0) {
      throw new RangeError(`invalid deposit: ${cents}`);
    }
    this.#balanceCents += cents;
    return this;                     // returning this allows chaining
  }

  withdraw(cents) {
    if (cents > this.#balanceCents) {
      throw new RangeError("insufficient funds");
    }
    this.#balanceCents -= cents;
    return this;
  }

  get balance() {                    // a getter: read like a property
    return (this.#balanceCents / 100).toFixed(2);
  }

  toString() {
    return `#${this.id} ${this.owner}: ${this.balance}`;
  }

  static fromJSON(data) {            // a static method: called on the class
    return new Account(data.owner, data.cents);
  }
}

class SavingsAccount extends Account {
  constructor(owner, openingCents, ratePercent) {
    super(owner, openingCents);      // run the parent constructor first
    this.ratePercent = ratePercent;
  }

  addInterest() {
    const cents = Math.round(Number(this.balance) * this.ratePercent);
    return this.deposit(cents);
  }

  toString() {
    return `${super.toString()} (savings, ${this.ratePercent}%)`;
  }
}

const kwame = new Account("Kwame", 5000).deposit(2550).withdraw(1000);
const lucia = new SavingsAccount("Lucía", 100000, 3);
lucia.addInterest();
const imported = Account.fromJSON({ owner: "Priya", cents: 999 });

for (const account of [kwame, lucia, imported]) {
  console.log(String(account));
}

try {
  kwame.withdraw(1_000_000);
} catch (err) {
  console.log(`${err.name}: ${err.message}`);
}

console.log(kwame.balanceCents, Object.keys(kwame));
console.log(lucia instanceof SavingsAccount, lucia instanceof Account, kwame instanceof SavingsAccount);
console.log(typeof Account, Object.getPrototypeOf(SavingsAccount.prototype) === Account.prototype);
text
#1 Kwame: 65.50
#2 Lucía: 1030.00 (savings, 3%)
#3 Priya: 9.99
RangeError: insufficient funds
undefined [ 'owner', 'id' ]
true true false
function true

What each part does:

  • Fields (owner;, #balanceCents = 0;) are created on each instance before the constructor body runs, which is why Object.keys(kwame) lists owner before id.
  • Private elements start with # (ECMAScript 2022). They are enforced by the language: kwame.balanceCents is simply a different, missing property, and writing kwame.#balanceCents outside the class is a syntax error, so the program would not even start. Before #, the convention was an underscore (_balance), which only asked others not to touch it.
  • Methods go on the prototype, shared by all instances. toString is called automatically by String(account) and by template literals.
  • Getters (get balance()) are read like properties. There is no setter here, so balance is read-only from outside: assigning to it would throw in strict mode.
  • Static members belong to the class itself: Account.fromJSON(...), and the private counter Account.#nextId. A static "factory" method like fromJSON is a common way to offer several ways of constructing an object.
  • Inheritance: SavingsAccount extends Account sets up the prototype chain; its constructor must call super(...) before using this; super.toString() calls the parent's version of an overridden method. instanceof walks the prototype chain.
  • It is all prototypes underneath: typeof Account is "function", and the last line confirms the link between the two prototypes.

When to use a class

Use a class when you have many objects with the same behaviour and state that must be protected by rules, like the account above, whose balance can only change through deposit and withdraw. For plain data (an API response, a configuration, a row from a table), a plain object literal is simpler and serialises to JSON directly. For a handful of related operations with no state, a module of plain functions is simplest of all. Keep inheritance hierarchies shallow: one level, as here, is common and clear; deep hierarchies make it hard to know which method actually runs. The usual advice is to prefer composition, an object that holds another (an Order with a customer property) over inheritance, an object that is another, unless the "is a" relationship is genuinely true.

Duck typing

JavaScript code rarely asks what class an object belongs to. It asks whether the object has what the code needs: if it has a toString method, String(x) will call it; if it has a then method, await will treat it as a promise; if it has a Symbol.iterator method, for...of can loop over it (lesson six). This is called duck typing, after the saying "if it walks like a duck and quacks like a duck, it is a duck". It is why a plain object literal with the right methods can stand in for a class instance in a test, and why instanceof checks are uncommon in idiomatic code: they fail for objects from another source (a different library copy, another browser frame) that would otherwise work perfectly. Check for the capability you need, or, in TypeScript, describe it with an interface.

ComputationC

Copies, freezing and JSON

Since objects are references, copying is something you do on purpose, and you must choose how deep the copy goes:

javascript
// Copying, freezing and JSON.
const order = {
  id: "A-1042",
  items: [{ sku: "tea", qty: 2 }],
  placed: new Date(Date.UTC(2026, 10, 19, 9, 30)),
};

// A spread copy is shallow: nested objects are shared.
const shallow = { ...order, id: "A-1043" };
shallow.items.push({ sku: "honey", qty: 1 });
console.log(order.items.length, shallow.id, order.id);

// structuredClone copies deeply (and understands Dates, Maps, Sets...).
const deep = structuredClone(order);
deep.items.push({ sku: "lemon", qty: 3 });
console.log(order.items.length, deep.items.length, deep.placed instanceof Date);

// Object.freeze makes the top level read-only (also shallow).
const settings = Object.freeze({ theme: "dark", sizes: [12, 14] });
try {
  settings.theme = "light";
} catch (err) {
  console.log(err.name);
}
settings.sizes.push(16);
console.log(settings.theme, settings.sizes);

// JSON: text in, text out. Dates become strings; functions and undefined vanish.
const text = JSON.stringify({ ...order, note: undefined, total() { return 0; } }, null, 2);
console.log(text);
const back = JSON.parse(text);
console.log(typeof back.placed, back.items[1].sku);
text
2 A-1043 A-1042
2 3 true
TypeError
dark [ 12, 14, 16 ]
{
  "id": "A-1042",
  "items": [
    {
      "sku": "tea",
      "qty": 2
    },
    {
      "sku": "honey",
      "qty": 1
    }
  ],
  "placed": "2026-11-19T09:30:00.000Z"
}
string honey
  • { ...order } copies the top-level properties into a new object, and you can override some in the same breath (id: "A-1043"). But items in the copy is the same array, so pushing to it changed the original order too. That is a shallow copy.
  • structuredClone (available in browsers and Node since 2022) makes a deep copy of plain data, including dates, maps, sets and nested arrays. It cannot copy functions or class instances' methods. It is the modern replacement for the old JSON.parse(JSON.stringify(x)) trick, which loses dates and undefined.
  • Object.freeze stops changes to an object's own properties; in strict mode, an attempted change throws a TypeError. It is shallow too: the frozen object's array can still grow.
  • JSON.stringify turns data into JSON text (the extra arguments null, 2 ask for two-space indentation), and JSON.parse turns it back. JSON has strings, numbers, booleans, null, arrays and objects, and nothing else, so a Date becomes an ISO string (and comes back as a string, as typeof back.placed shows), while functions and undefined properties disappear. A class can control its own serialisation by defining a toJSON method.

Note the month in Date.UTC(2026, 10, 19, ...): JavaScript's Date numbers months from 0, so 10 is November, a decades-old trap. A new date-and-time API, Temporal, fixes this and much else; as of 2026 it is being rolled out across engines, so check MDN's compatibility table before relying on it.

Common misconceptionsH

Common misconceptions

Misconception

"JavaScript classes work like Java or C# classes." The syntax is similar, but underneath an instance simply delegates to a prototype object, which can be inspected and even changed at run time. There are no class-level type checks, and a method is just a function property: it can be borrowed, detached (losing this) or replaced.

Misconception

"const obj = {...} makes the object immutable." It only stops the name from being reassigned. Use Object.freeze for a shallow read-only object, or simply treat data as immutable by convention and create changed copies with spread.

Misconception

"a === b tells me whether two objects contain the same data." It tells you whether they are the same object. To compare contents, compare the fields you care about, or use a test library's deep-equality assertion (lesson seven).

Misconception

"A plain object is a good dictionary for arbitrary keys." It works for fixed, known keys. For keys that come from users or data, a plain object can collide with inherited names such as constructor or toString, and its keys are always strings. A Map (next lesson) has none of these problems.

Exercises

Exercises

For each program, trace the property lookups and references by hand before you run it.

1. Objects, prototypes and classes

Warm-upComputational

What does this print?

const u = { profile: null };
console.log(u.profile?.email ?? "none", u.settings?.theme);

2. Objects, prototypes and classes

CoreComputational

What does this print?

const p = { tags: ["a"] };
const q = { ...p };
q.tags.push("b");
q.name = "x";
console.log(p.tags.length, p.name);

3. Objects, prototypes and classes

CoreComputational

What does this print?

const base = { greet() { return "hi from " + this.name; }, name: "base" };
const child = Object.create(base);
child.name = "child";
console.log(child.greet(), Object.keys(child).length);

4. Objects, prototypes and classes

CoreComputational

What does this print?

class Shape {
  area() { return 0; }
  describe() { return `area ${this.area()}`; }
}
class Square extends Shape {
  constructor(side) {
    super();
    this.side = side;
  }
  area() { return this.side ** 2; }
}
console.log(new Square(3).describe(), new Shape().describe());

5. Objects, prototypes and classes

CoreComputational

What does this print?

const data = { a: 1, b: undefined, c: () => 1, d: [undefined, 2] };
console.log(JSON.stringify(data));

6. Objects, prototypes and classes

StretchComputational

What happens when Node runs this module?

class Safe {
  #code = 1234;
}
const s = new Safe();
console.log(s.#code);
Choose one

7. Objects, prototypes and classes

StretchHuman

Which of these is the best candidate for a class, rather than a plain object literal or a module of functions?

Choose one

Further reading and resources