Appearance
Objects, Prototypes and Classes
23. What are prototypes and the prototype chain?
The short answer
Every JavaScript object has a hidden link to another object, called its prototype. When you read a property the object does not have, the engine looks in its prototype, then in the prototype's prototype, and so on, until it finds the property or reaches null at the end. That series of links is the prototype chain. It is how all arrays share methods like map, and how classes share methods between instances without copying them.
An everyday example you already use:
ts
const prices = [3, 9, 4]
prices.map((p) => p * 2) // prices has no own "map" propertyprices itself only holds the numbers and length. map is found one step up the chain, on Array.prototype.
map is not on the array, so the engine finds it on Array.prototype. ② toString is two steps up. ③ A name found nowhere before null gives undefined.Seeing the chain yourself:
ts
const prices = [3, 9, 4]
Object.getPrototypeOf(prices) === Array.prototype // true
Object.getPrototypeOf(Array.prototype) === Object.prototype // true
Object.getPrototypeOf(Object.prototype) // null
Object.hasOwn(prices, 'map') // false: inheritedTwo names that confuse everyone:
| Name | What it is |
|---|---|
obj.__proto__, or Object.getPrototypeOf(obj) | The object's own link to its prototype |
Fn.prototype | A property on a function: the object that becomes the prototype of things created with new Fn() |
So new Order() creates an object whose __proto__ is Order.prototype.
Writing is different from reading. Reading walks up the chain. Assigning, prices.map = …, creates an own property on the object itself, which then shadows the inherited one. It does not change Array.prototype.
Never extend built-in prototypes in application code, such as adding Array.prototype.sum. Every array in the program, and every library, sees it, and a future version of JavaScript may add a method with the same name.
24. What is prototypal inheritance?
The short answer
Prototypal inheritance means objects inherit directly from other objects: an object can use the properties and methods of its prototype as if they were its own. There are no classes underneath; an object simply links to another object and borrows from it. Object.create(proto) makes that link directly, constructor functions with new make it through Fn.prototype, and the class keyword is a cleaner syntax for the same mechanism.
Inheritance without any class, using Object.create:
js
const baseAccount = {
describe() { // (1)
return `${this.owner}: £${this.balance}`
},
}
const savings = Object.create(baseAccount) // (2)
savings.owner = 'Priya'
savings.balance = 1200
console.log(savings.describe()) // (3) 'Priya: £1200'
console.log(Object.getPrototypeOf(savings) === baseAccount) // true- A shared method lives once, on
baseAccount. Object.createmakes a new, empty object whose prototype isbaseAccount.describeis found on the prototype, butthisissavings, because it was called assavings.describe()(question 15).
The old way, with a constructor function:
js
function Account(owner, balance) {
this.owner = owner
this.balance = balance
}
Account.prototype.describe = function () {
return `${this.owner}: £${this.balance}`
}
const a = new Account('Ravi', 300)new does four things: creates an empty object, links it to Account.prototype, runs Account with this set to the new object, and returns it.
How it differs from classical inheritance, as in Java or C#:
| Classical | Prototypal | |
|---|---|---|
| Inherits from | A class, a blueprint | Another object |
| Relationship | Fixed when compiled | A live link; can be changed at runtime |
| Methods | Copied into each class's definition | Shared through the chain, looked up when called |
A live link means that adding a method to the prototype later makes it available to every object already linked to it. That is powerful, and it is also why changing shared prototypes is risky.
In modern code, you mostly use class (question 25), and favour composition, combining small objects or functions, over deep inheritance chains.
25. How do JavaScript classes relate to prototypes?
The short answer
A JavaScript class is syntax over prototypes, not a new object model. The class body's methods are placed on ClassName.prototype and shared by every instance through the prototype chain. extends links one class's prototype to another's, and super calls the parent's version. Classes add real improvements on top: they are always in strict mode, must be called with new, are not usable before their declaration, and support private fields and static members.
ts
class Order {
constructor(public id: string, public total: number) {} // (1)
describe() { // (2)
return `Order ${this.id}: £${this.total}`
}
}
class GiftOrder extends Order { // (3)
constructor(id: string, total: number, public message: string) {
super(id, total) // (4)
}
describe() {
return `${super.describe()} (gift: ${this.message})` // (5)
}
}
const g = new GiftOrder('A12', 40, 'Happy birthday')
console.log(g.describe()) // Order A12: £40 (gift: Happy birthday)- The constructor sets own properties on each instance.
public idis TypeScript's shorthand for declaring and assigning the property. - Methods go on the prototype:
Order.prototype.describe. All orders share one copy. extendslinksGiftOrder.prototypetoOrder.prototype.super(...)calls the parent constructor. It must run beforethisis used in a subclass constructor.super.describe()calls the parent's method.
The same thing, proven:
ts
typeof Order // 'function'
Object.hasOwn(g, 'describe') // false
Object.getPrototypeOf(GiftOrder.prototype) === Order.prototype // trueWhat classes add over constructor functions:
| Feature | Constructor function | Class |
|---|---|---|
Calling without new | Silently runs with the wrong this | TypeError |
| Strict mode | Only if declared | Always |
| Hoisting | Fully hoisted | Temporal dead zone (question 10) |
Private fields #x | No | Yes (question 26) |
static members, extends, super | Manual wiring | Built in |
Composition over deep inheritance. Two levels of extends is usually fine. Five levels make code hard to change, because every child depends on details of every parent. Prefer small classes or functions combined together: an Order that has a PricingPolicy, rather than DiscountedSeasonalGiftOrder extends ....
26. What are private fields and static members in classes?
The short answer
A private field, written with a # such as #balance, can only be read or changed by code inside the class body; outside code gets a SyntaxError if it tries, so the privacy is enforced by the engine at runtime. A static member, declared with static, belongs to the class itself rather than to each instance, which suits shared constants, counters and factory methods.
ts
class Wallet {
static #created = 0 // (1)
static readonly CURRENCY = 'GBP' // (2)
#balance = 0 // (3)
constructor() { Wallet.#created += 1 }
deposit(amount: number) {
if (amount <= 0) throw new Error('amount must be positive')
this.#balance += amount // (4)
}
get balance() { return this.#balance } // (5)
static count() { return Wallet.#created } // (6)
}
const w = new Wallet()
w.deposit(50)
console.log(w.balance) // 50
console.log(Wallet.count()) // 1
// w.#balance = 1000 // SyntaxError: private field- A static private field: one counter for the whole class, hidden from outside.
- A static public constant, read as
Wallet.CURRENCY. - A private instance field: each wallet has its own, and no outside code can touch it.
- Only methods inside the class can change it, so every change goes through the validation in
deposit. - A getter exposes the value read-only (question 31).
- A static method, called on the class:
Wallet.count().
#private versus TypeScript's private:
#balance | private balance | |
|---|---|---|
| Enforced by | The JavaScript engine, at runtime | The TypeScript compiler only |
| Visible after compiling | No | Yes, it is a normal property |
| Bypass | Impossible | (w as any).balance works |
Use # when the privacy must really hold, such as in a library. TypeScript's private is fine for normal application code where the type checker is enough.
27. What is the difference between Object.freeze, Object.seal, and const?
The short answer
const only stops the variable from being reassigned; the object it points to can still be changed. Object.seal stops adding and deleting properties, but existing properties can still be changed. Object.freeze stops adding, deleting and changing properties. Both freeze and seal are shallow: nested objects inside stay fully changeable unless you freeze them too.
| Reassign variable | Add property | Delete property | Change property | |
|---|---|---|---|---|
const | No | Yes | Yes | Yes |
Object.seal | Depends on let or const | No | No | Yes |
Object.freeze | Depends on let or const | No | No | No |
js
'use strict'
const config = Object.freeze({
currency: 'GBP',
limits: { maxItems: 50 }, // (1)
})
config.currency = 'EUR' // (2) TypeError: read-only
config.limits.maxItems = 999 // (3) allowed: nested object not frozen
config = {} // (4) TypeError: assignment to constant- A nested object, not frozen by the outer
freeze. - Changing a frozen property throws in strict mode, and is silently ignored in sloppy mode.
- Shallow: the inner object can still change.
constblocks reassigning the variable itself.
Deep freeze, when you really need it:
ts
function deepFreeze<T extends object>(obj: T): Readonly<T> {
for (const value of Object.values(obj)) {
if (value && typeof value === 'object') deepFreeze(value)
}
return Object.freeze(obj)
}In practice: freezing is useful for shared configuration and constants. TypeScript's readonly and as const give the same protection at compile time with no runtime cost, which is enough for most application code.
28. What are symbols in JavaScript?
The short answer
A symbol is a primitive value that is guaranteed to be unique, created with Symbol('description'). Its main use is as a property key that can never clash with any other key, even one with the same description. Symbol keys are skipped by for...in, Object.keys and JSON.stringify. JavaScript also has well-known symbols, such as Symbol.iterator, that let your objects plug into built-in behaviour like for...of.
ts
const internalId = Symbol('internalId') // (1)
const order = {
id: 'A12',
[internalId]: 'db-88231', // (2)
}
console.log(Symbol('x') === Symbol('x')) // (3) false
console.log(Object.keys(order)) // ['id']
console.log(JSON.stringify(order)) // {"id":"A12"}
console.log(order[internalId]) // 'db-88231'- A new, unique symbol. The description is only a label for debugging.
- Used as a key with computed property syntax.
- Every symbol is unique, even with the same description.
Well-known symbols, which customise built-in behaviour:
| Symbol | Lets your object |
|---|---|
Symbol.iterator | Work with for...of and spread (question 46) |
Symbol.asyncIterator | Work with for await...of |
Symbol.toPrimitive | Control conversion to a number or string |
Symbol.dispose | Clean up with the new using declarations |
Symbol.for('key') returns a shared, global symbol for that key, so different files can get the same symbol. Use it when separate modules must agree on one key.
Not really private. Symbol keys are hidden from normal listing, but Object.getOwnPropertySymbols(order) still finds them. For real privacy, use #private fields (question 26).
29. When should you use a Map instead of a plain object?
The short answer
Use a Map when you need a dictionary: keys added and removed at runtime, keys that are not strings, such as objects or numbers, frequent additions and deletions, or a reliable count with .size. Use a plain object for records with a known, fixed set of named fields, such as a user or an order, and for data you will turn into JSON. Maps also never collide with inherited keys like toString or __proto__.
Map | Plain object | |
|---|---|---|
| Key types | Any value: objects, numbers, strings | Strings and symbols only |
| Order | Insertion order, always | Mostly insertion order, but integer-like keys come first |
| Size | map.size | Object.keys(obj).length |
| Inherited keys | None | toString, constructor, __proto__ can clash |
| Iteration | Directly with for...of | Through Object.keys, entries |
| JSON | Not directly | Yes |
| Best for | Dynamic lookups, caches, counting | Fixed-shape records |
A real case: object keys.
ts
const lastSeen = new Map<HTMLElement, number>()
lastSeen.set(document.body, Date.now()) // an element as a key
const counts: Record<string, number> = {}
counts[String(document.body)] = 1 // key becomes "[object HTMLBodyElement]"With a plain object, every element would turn into the same string key.
The prototype trap with user-supplied keys:
ts
const stock: Record<string, number> = {}
const sku = '__proto__' // from a request
stock[sku] = 5 // does not create a normal keyUser input as object keys can hit special names. A Map, or Object.create(null), avoids that. Assigning attacker-controlled keys into objects is also the root of prototype pollution attacks, covered in the security module.
Counting with a Map:
ts
function countByStatus(orders: { status: string }[]) {
const counts = new Map<string, number>()
for (const o of orders) counts.set(o.status, (counts.get(o.status) ?? 0) + 1)
return counts
}30. What are WeakMap and WeakSet for?
The short answer
A WeakMap is a map whose keys must be objects and are held weakly: if nothing else refers to a key object, the garbage collector can remove it, and its entry disappears with it. A WeakSet does the same for a set of objects. They are used to attach extra data or flags to objects you do not own, such as DOM nodes or request objects, without stopping those objects from being freed. Because entries can vanish at any time, you cannot list them or ask for their size.
ts
const requestStart = new WeakMap<object, number>() // (1)
function onRequestStart(req: object) {
requestStart.set(req, performance.now()) // (2)
}
function onRequestEnd(req: object) {
const start = requestStart.get(req)
if (start !== undefined) console.log('took', performance.now() - start, 'ms')
} // (3)- A WeakMap keyed by request objects.
- Attach data to an object without adding a property to it.
- No clean-up needed. When the request object is no longer used anywhere, it is freed, and its entry goes with it. With a normal
Map, every request would stay in memory for ever, a leak (question 14).
Map | WeakMap | |
|---|---|---|
| Key types | Anything | Objects, and non-registered symbols |
| Keeps keys alive | Yes | No |
Iterate, .size, .clear() | Yes | No |
| Use | General dictionaries | Data attached to objects whose lifetime you do not control |
Common uses:
- Caching results per object, such as a computed layout per DOM element.
- Private data per instance, the pattern used before
#privatefields existed. - Marking objects as seen, with a
WeakSet, for example to avoid processing the same object twice in a deep clone with cycles.
WeakRef and FinalizationRegistry go further, letting you hold a weak reference to a single object, or run code after an object is collected. They are for rare, advanced cases, because garbage collection timing is not predictable.
31. What are getters, setters, and Proxy?
The short answer
A getter is a function that runs when a property is read, and a setter runs when it is assigned, so a property can be computed or validated while still looking like a plain field. A Proxy wraps a whole object and lets you intercept almost any operation on it, such as reading, writing, deleting or checking for a property, through handler functions called traps. Reflect provides the default behaviour of each of those operations, so a trap can add its logic and then pass the operation on.
Getters and setters:
ts
class CartLine {
#qty = 1
constructor(public unitPrice: number) {}
get total() { // (1)
return this.unitPrice * this.#qty
}
set qty(value: number) { // (2)
if (!Number.isInteger(value) || value < 1) throw new RangeError('qty must be a whole number ≥ 1')
this.#qty = value
}
}
const line = new CartLine(4.5)
line.qty = 3
console.log(line.total) // 13.5, computed on read
line.qty = 0 // RangeError- A getter:
line.totalreads like a field, but it is computed every time. - A setter: assignment runs validation, so bad values never get stored.
A Proxy, logging every change to a settings object:
ts
function watch<T extends object>(target: T, onChange: (key: string, value: unknown) => void): T {
return new Proxy(target, {
set(obj, key, value, receiver) { // (1)
onChange(String(key), value)
return Reflect.set(obj, key, value, receiver) // (2)
},
})
}
const settings = watch({ theme: 'light' }, (k, v) => console.log('changed', k, v))
settings.theme = 'dark' // changed theme dark- A
settrap runs for every assignment to the proxy. Reflect.setdoes the normal assignment, so the trap adds behaviour without re-implementing it. It returnstrueon success, which the trap must return.
Where Proxies are used in real tools:
- Reactivity: Vue 3 and MobX track which properties a component reads and re-render when they change.
- Validation and defaults on configuration objects.
- Immutable updates: Immer, used inside Redux Toolkit, lets you "mutate" a draft proxy and produces a new object.
The cost: every operation on a proxy goes through a function call, so they are slower than plain objects, and they make behaviour less obvious to someone reading the code. Use them in libraries and infrastructure, not for ordinary business objects.