JavaScript · Lesson 5
Objects and Prototypes
What a JavaScript object really is (a set of properties plus a link to another object), how lookups walk the prototype chain, and how to copy, freeze, compare and serialize objects without surprises.
In short
- An object is own properties plus a prototype link
- Reads walk the chain; writes land on the object
Object.hasOwnfor own keys;Object.create(null)for dictionaries- Spread is shallow;
structuredCloneis deep but drops prototypes - JSON loses Dates,
undefined, Maps and Sets ===compares identity; freeze is shallow
In C# an object is an instance of a class, and its shape is fixed at compile time. In JavaScript an object is much simpler and much more flexible: it's a set of properties plus a hidden link to another object, its prototype. You can add and remove properties at any time, and when you read a property the object doesn't have, JavaScript asks its prototype, then the prototype's prototype, and so on.
Almost everything in this lesson follows from that one picture:
- an object holds own properties (each with a value and a few flags),
- it has one prototype link (or
null), - a read walks the chain until it finds the key; a write always lands on the object itself.
Every js snippet has a ▶ Try button. Predict the output, then run it.
Object literals
const name = 'Ann';
const field = 'role';
const user = {
name, // shorthand for name: name
[field]: 'admin', // computed key: the key is the value of `field`
[`is${'Active'}`]: true, // any expression works
greet() { // method shorthand
return `Hi, I'm ${this.name}`;
},
};
console.log(user.role, user.isActive, user.greet());
console.log(Object.keys(user));
- Shorthand properties (
{ name }) and methods (greet() {}) save typing. A shorthand method is a normal function property, andthisis the object it was called on. - Computed keys (
[expr]: value) are how you build an object whose keys come from data. - Spread (
{ ...a, ...b }) copies own enumerable properties. Later keys win, so{ ...defaults, ...overrides }is the standard "defaults plus overrides" pattern.
Keys are strings (or symbols)
Property keys are always strings or symbols. Anything else is converted to a string first:
const scores = {};
scores[1] = 'one';
scores['1'] = 'still one'; // same key: 1 became '1'
scores[{}] = 'object'; // the key is '[object Object]'
scores[{ id: 2 }] = 'oops'; // the same key again!
console.log(Object.keys(scores));
console.log(scores['[object Object]']);
That last line is why you need a Map when the keys are objects. A Map keeps keys of any type,
compares them by identity, and has a real size.
Property order is defined, but not what you expect
Object.keys, for...in, spread and JSON.stringify all use the same order:
- Integer-like keys (
'0','7','42') in ascending numeric order, - then other string keys in insertion order,
- then symbols, in insertion order (only
Reflect.ownKeysandObject.getOwnPropertySymbolsshow them).
const byId = {};
byId.b = 'B';
byId['10'] = 'ten';
byId.a = 'A';
byId['2'] = 'two';
console.log(Object.keys(byId)); // integer keys first, sorted, then insertion order
If you keep records "in the order the server sent them" in an object keyed by numeric id, the order is
gone. Keep an array (or a Map, which always keeps insertion order).
Reading and writing
obj.keyandobj['key']do the same thing. Use brackets for keys that aren't identifiers or come from variables.- Reading a missing property gives
undefined, not an error. Reading a property ofundefinedthrows, which is what optional chaining is for:order?.customer?.address?.city. ??gives a fallback only fornullandundefined.||also replaces0,''andfalse, which is usually a bug for counts and flags.delete obj.keyremoves an own property. Setting it toundefinedkeeps the key (it still shows inObject.keysandin).
Property descriptors
Each property is more than a value. It has flags:
| Flag | Meaning | Default in a literal | Default with defineProperty |
|---|---|---|---|
writable | the value can be changed | true | false |
enumerable | shows up in Object.keys, for...in, spread, JSON | true | false |
configurable | can be deleted, or its flags changed | true | false |
const order = { id: 7 };
Object.defineProperty(order, 'internalNote', {
value: 'VIP customer',
enumerable: false, // hidden from keys, spread and JSON
});
console.log(Object.keys(order), JSON.stringify(order));
console.log(order.internalNote);
console.log(Object.getOwnPropertyDescriptor(order, 'id'));
try {
order.internalNote = 'changed'; // writable is false (the default for defineProperty)
} catch (e) {
console.log(e.constructor.name, e.message);
}
In strict mode (modules, classes and every exercise here), writing to a read-only property throws a
TypeError. In old sloppy scripts the write is silently ignored, which is far worse to debug.
Getters and setters
A property can be an accessor: a get function that runs on read and a set function that runs
on write. To the caller it looks like a plain property.
const temperature = {
celsius: 20,
get fahrenheit() {
return this.celsius * 9 / 5 + 32;
},
set fahrenheit(f) {
if (typeof f !== 'number') throw new TypeError('fahrenheit must be a number');
this.celsius = (f - 32) * 5 / 9;
},
};
console.log(temperature.fahrenheit); // computed on read
temperature.fahrenheit = 212; // runs the setter
console.log(temperature.celsius);
A getter with no setter is read-only: assigning to it throws in strict mode. Getters are great for derived values. Keep them cheap and free of side effects, because callers treat them like fields.
Listing and building objects
| You want | Use | Includes inherited? | Includes non-enumerable? | Includes symbols? |
|---|---|---|---|---|
| keys / values / pairs | Object.keys / values / entries | no | no | no |
| loop over keys | for...in | yes (enumerable ones) | no | no |
| every own key | Reflect.ownKeys | no | yes | yes |
Object.fromEntries turns pairs back into an object, so "transform an object" is
entries, then array methods, then fromEntries:
const prices = { apple: 1.2, pear: 0.8, mango: 2.5 };
const withVat = Object.fromEntries(
Object.entries(prices).map(([fruit, price]) => [fruit, Math.round(price * 1.2 * 100) / 100]),
);
const cheap = Object.fromEntries(Object.entries(prices).filter(([, price]) => price < 2));
console.log(withVat);
console.log(cheap);
console.log(Object.fromEntries(new Map([['a', 1], ['b', 2]]))); // any iterable of pairs works
Prefer Object.keys/entries to for...in. for...in also visits enumerable properties inherited
from the prototype chain, which is rarely what you want.
The prototype chain
Every object has an internal link, [[Prototype]], to another object or to null. Read it with
Object.getPrototypeOf(obj). When you read obj.key:
- If
objhas an own propertykey, that's the answer. - Otherwise, look in its prototype, then that object's prototype, and so on.
- If the chain ends at
nullwithout finding it, the result isundefined.
const animal = {
describe() {
return `${this.name} says ${this.sound}`;
},
sound: '...',
};
const dog = Object.create(animal); // a new, empty object whose prototype is `animal`
dog.name = 'Rex';
dog.sound = 'woof'; // an own property that shadows animal.sound
const fish = Object.create(animal);
fish.name = 'Nemo'; // no own `sound`: the read falls through to animal
console.log(dog.describe());
console.log(fish.describe());
console.log(Object.getPrototypeOf(dog) === animal);
console.log(Object.keys(dog)); // only own properties
Key points:
- Reads walk the chain. Writes don't.
dog.sound = 'woof'creates an own property ondog. It never changesanimal. (The exception: if the chain has a setter for that key, the setter runs.) - Methods are shared.
describeexists once, onanimal, and every object that inherits from it uses it.thisis the object the method was called on (dogorfish), not where the method lives. - The chain is live. Add a method to
animallater anddogsees it at once. - A plain
{}inherits fromObject.prototype, which is wheretoString,hasOwnPropertyandconstructorcome from. Arrays inherit fromArray.prototype, which inherits fromObject.prototype.
const arr = [1, 2];
console.log(Object.getPrototypeOf(arr) === Array.prototype);
console.log(Object.getPrototypeOf(Array.prototype) === Object.prototype);
console.log(Object.getPrototypeOf(Object.prototype)); // the end of every chain
Objects with no prototype
Object.create(null) makes an object with no prototype: no toString, no constructor, no
__proto__ magic. That makes it a safe dictionary for keys that come from users:
const counts = {};
for (const word of ['constructor', 'toString', 'constructor']) {
counts[word] = (counts[word] || 0) + 1; // reads inherited functions!
}
console.log(counts.constructor); // not 2!
const safe = Object.create(null);
for (const word of ['constructor', 'toString', 'constructor']) {
safe[word] = (safe[word] ?? 0) + 1;
}
console.log(safe.constructor, safe.toString);
In the first loop, counts['constructor'] is the inherited Object function, which is truthy, so the
"count" becomes the string "function Object() { [native code] }1", then ...11. Use a Map or Object.create(null) for
dictionaries with arbitrary keys. The Word counts exercise is about exactly this.
in versus Object.hasOwn
const settings = Object.create({ theme: 'dark' }); // inherited default
settings.fontSize = 14;
settings.debug = undefined;
console.log('theme' in settings, Object.hasOwn(settings, 'theme'));
console.log('fontSize' in settings, Object.hasOwn(settings, 'fontSize'));
console.log('debug' in settings, settings.debug !== undefined);
console.log('toString' in settings, Object.hasOwn(settings, 'toString'));
key in objis true if the key is anywhere on the chain, includingtoString.Object.hasOwn(obj, key)is true only for own properties. It's the modern replacement forobj.hasOwnProperty(key), which breaks onObject.create(null)objects (they have no such method) and on objects that define their ownhasOwnProperty.obj.key !== undefinedcan't tell "missing" from "present but undefined".
Functions, prototype and new
Before classes, inheritance was written with constructor functions. Every normal function has a
prototype property, and new F() creates an object whose prototype is F.prototype:
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype.length = function () {
return Math.hypot(this.x, this.y);
};
const p = new Point(3, 4);
console.log(p.length());
console.log(Object.getPrototypeOf(p) === Point.prototype, p instanceof Point);
console.log(Object.keys(p)); // x and y are own; length is shared
Don't confuse the two: Point.prototype is the object that instances inherit from. The prototype
of Point itself is Function.prototype. instanceof simply checks whether Point.prototype is
somewhere on p's chain. The Classes topic shows that class builds exactly this structure.
Copying objects
Objects are passed and assigned by reference. const b = a doesn't copy anything.
Shallow copies
{ ...obj } and Object.assign({}, obj) copy the top level only. Nested objects are still shared:
const original = { name: 'Ann', address: { city: 'Oslo' }, tags: ['admin'] };
const copy = { ...original };
copy.name = 'Bob'; // fine: a top-level property of the copy
copy.address.city = 'Bergen'; // changes the shared nested object
copy.tags.push('beta');
console.log(original.name, original.address.city, original.tags);
Spread also drops things: non-enumerable properties, getters (it copies their current value), and the prototype. A spread copy of a class instance is a plain object without the class's methods.
Deep copies with structuredClone
structuredClone(value) (in every modern browser and Node 17+) makes a real deep copy. It handles
Date, Map, Set, RegExp, typed arrays, Error objects, and even cycles and shared references:
const state = {
createdAt: new Date('2024-05-01T00:00:00Z'),
tags: new Set(['a', 'b']),
byId: new Map([[1, { name: 'Ann' }]]),
};
state.self = state; // a cycle
const clone = structuredClone(state);
console.log(clone.createdAt instanceof Date, clone.createdAt !== state.createdAt);
console.log(clone.tags.has('a'), clone.byId.get(1).name);
console.log(clone.self === clone); // the cycle is rebuilt, pointing at the clone
What it can't do: functions (it throws a DataCloneError), DOM nodes, and prototypes. A class
instance comes back as a plain object, so its methods are gone. Getters are read and stored as values.
What a JSON round trip loses
JSON.parse(JSON.stringify(x)) used to be the "deep clone" trick. It quietly changes your data:
const input = {
when: new Date('2024-05-01T00:00:00Z'),
missing: undefined,
fn() {},
ids: new Set([1, 2]),
lookup: new Map([['a', 1]]),
ratio: NaN,
list: [undefined, 1],
};
const roundTrip = JSON.parse(JSON.stringify(input));
console.log(typeof roundTrip.when, roundTrip.when); // a string now
console.log('missing' in roundTrip, 'fn' in roundTrip); // dropped
console.log(roundTrip.ids, roundTrip.lookup); // empty objects
console.log(roundTrip.ratio, roundTrip.list); // NaN became null; undefined in arrays too
| Value | After a JSON round trip |
|---|---|
Date | an ISO string |
undefined, functions, symbols (as property values) | the key disappears |
undefined, functions in arrays | null |
NaN, Infinity | null |
Map, Set | {} |
| class instances | plain objects |
BigInt | throws a TypeError |
| cycles | throws a TypeError |
This matters every time data crosses a JSON boundary: an HTTP response, localStorage, a message queue,
or persisted state. (postMessage to a Web Worker uses structured cloning instead, which keeps Dates, Maps
and Sets.) Dates from an API are strings until you parse them.
Freezing and sealing
| add properties | delete properties | change values | |
|---|---|---|---|
Object.preventExtensions | no | yes | yes |
Object.seal | no | no | yes |
Object.freeze | no | no | no |
const config = Object.freeze({ apiUrl: '/api', retry: { count: 3 } });
try {
config.apiUrl = '/v2'; // TypeError in strict mode
} catch (e) {
console.log(e.constructor.name);
}
config.retry.count = 10; // allowed: freeze is shallow
console.log(config.apiUrl, config.retry.count, Object.isFrozen(config), Object.isFrozen(config.retry));
Object.freeze is shallow. To freeze a whole tree, walk it and freeze each nested object. Freezing in
development is a cheap way to catch code that mutates state it shouldn't (Redux Toolkit and Immer do this).
const is unrelated: it stops you reassigning the variable, not changing the object.
Comparing objects
=== and Object.is compare objects by identity: are these the same object in memory?
const a = { id: 1 };
const b = { id: 1 };
console.log(a === b, a === a);
console.log([1, 2] === [1, 2]);
console.log(NaN === NaN, Object.is(NaN, NaN), Object.is(0, -0));
There is no built-in deep equality. Common choices:
- Compare by identity on purpose. React's
useMemo,React.memoand Angular'sOnPushcheck whether a value is the same reference. That's why state updates create new objects instead of mutating: a new reference means "something changed". - Shallow equality: same keys, and each value
Object.isequal. Cheap, and whatReact.memodoes with props. - Deep equality: recursive, needs rules for Dates, Maps, Sets,
NaNand cycles. The Deep equal exercise builds one. Libraries:node:util'sisDeepStrictEqual, lodashisEqual. JSON.stringify(a) === JSON.stringify(b)is fragile: key order matters, and it inherits every loss in the table above.
Coming from C# and TypeScript
Side note
- There are no structs and no value-type objects. Every object is a reference, like a C# class, and
==never compares fields. C#recordequality has no built-in equivalent. - TypeScript types disappear at runtime. A
UserfromJSON.parseis whatever the server sent, with string dates and maybe missing fields. Validate at the boundary (zod, valibot, or hand-written checks). - An object used as a dictionary is like
Dictionary<string, T>, but it inherits keys fromObject.prototype. AMapis the closer match. readonlyin TypeScript is compile time only.Object.freezeis the runtime version.- Prototype inheritance is delegation, not copying. Changing a prototype changes every object that inherits from it, immediately.
In real codebases
Side note
- Immutable updates. React state, Redux reducers and Angular signals with
OnPushall rely on new references:{ ...state, user: { ...state.user, name } }. Mutating in place leaves the old reference and the UI doesn't update. Libraries like Immer let you write mutations that produce copies. - Config merging. Defaults plus environment plus user settings is a deep merge. Watch for arrays
(replace or concatenate?) and for
undefinedmeaning "not set". - Prototype pollution is a real class of security bug. A deep merge or path setter that copies a
__proto__key from user JSON can write intoObject.prototypeand change every object in the process. Skip__proto__,constructorandprototypekeys, or useObject.create(null)andMap. - Dates across the wire. API responses carry ISO strings. Parse them at the edge, not in every component.
structuredCloneis the default for deep copies today. Reach for a hand-written clone only when you need to keep prototypes or copy functions.
The exercises
- pick and omit: own keys only, and "missing" versus "undefined".
- Word counts: a dictionary that survives
constructorand__proto__. - get by path: read
'orders[0].items[2].sku'safely. - Inheritance without class: wire constructor functions and prototypes by hand.
- Object diff: what changed between two versions of a record.
- Deep merge: layered config without mutation and without prototype pollution.
- Deep equal: compare Dates, Maps, Sets,
NaNand cycles. - Deep clone: copy a graph with Dates, Maps, Sets, cycles and class instances.
Practise this lesson
In the app: a short video, 8 exercises checked by real tests and a 12-question concept check. Free with a GitHub account.
Open in the app