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.

14 min read

In short

  • An object is own properties plus a prototype link
  • Reads walk the chain; writes land on the object
  • Object.hasOwn for own keys; Object.create(null) for dictionaries
  • Spread is shallow; structuredClone is 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

▶ Try
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, and this is 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:

▶ Try
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:

  1. Integer-like keys ('0', '7', '42') in ascending numeric order,
  2. then other string keys in insertion order,
  3. then symbols, in insertion order (only Reflect.ownKeys and Object.getOwnPropertySymbols show them).
▶ Try
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.key and obj['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 of undefined throws, which is what optional chaining is for: order?.customer?.address?.city.
  • ?? gives a fallback only for null and undefined. || also replaces 0, '' and false, which is usually a bug for counts and flags.
  • delete obj.key removes an own property. Setting it to undefined keeps the key (it still shows in Object.keys and in).

Property descriptors

Each property is more than a value. It has flags:

FlagMeaningDefault in a literalDefault with defineProperty
writablethe value can be changedtruefalse
enumerableshows up in Object.keys, for...in, spread, JSONtruefalse
configurablecan be deleted, or its flags changedtruefalse
▶ Try
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.

▶ Try
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 wantUseIncludes inherited?Includes non-enumerable?Includes symbols?
keys / values / pairsObject.keys / values / entriesnonono
loop over keysfor...inyes (enumerable ones)nono
every own keyReflect.ownKeysnoyesyes

Object.fromEntries turns pairs back into an object, so "transform an object" is entries, then array methods, then fromEntries:

▶ Try
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:

  1. If obj has an own property key, that's the answer.
  2. Otherwise, look in its prototype, then that object's prototype, and so on.
  3. If the chain ends at null without finding it, the result is undefined.
▶ Try
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 on dog. It never changes animal. (The exception: if the chain has a setter for that key, the setter runs.)
  • Methods are shared. describe exists once, on animal, and every object that inherits from it uses it. this is the object the method was called on (dog or fish), not where the method lives.
  • The chain is live. Add a method to animal later and dog sees it at once.
  • A plain {} inherits from Object.prototype, which is where toString, hasOwnProperty and constructor come from. Arrays inherit from Array.prototype, which inherits from Object.prototype.
▶ Try
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:

▶ Try
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

▶ Try
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 obj is true if the key is anywhere on the chain, including toString.
  • Object.hasOwn(obj, key) is true only for own properties. It's the modern replacement for obj.hasOwnProperty(key), which breaks on Object.create(null) objects (they have no such method) and on objects that define their own hasOwnProperty.
  • obj.key !== undefined can'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:

▶ Try
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:

▶ Try
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:

▶ Try
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:

▶ Try
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
ValueAfter a JSON round trip
Datean ISO string
undefined, functions, symbols (as property values)the key disappears
undefined, functions in arraysnull
NaN, Infinitynull
Map, Set{}
class instancesplain objects
BigIntthrows a TypeError
cyclesthrows 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 propertiesdelete propertieschange values
Object.preventExtensionsnoyesyes
Object.sealnonoyes
Object.freezenonono
▶ Try
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?

▶ Try
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.memo and Angular's OnPush check 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.is equal. Cheap, and what React.memo does with props.
  • Deep equality: recursive, needs rules for Dates, Maps, Sets, NaN and cycles. The Deep equal exercise builds one. Libraries: node:util's isDeepStrictEqual, lodash isEqual.
  • 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# record equality has no built-in equivalent.
  • TypeScript types disappear at runtime. A User from JSON.parse is 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 from Object.prototype. A Map is the closer match.
  • readonly in TypeScript is compile time only. Object.freeze is 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 OnPush all 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 undefined meaning "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 into Object.prototype and change every object in the process. Skip __proto__, constructor and prototype keys, or use Object.create(null) and Map.
  • Dates across the wire. API responses carry ISO strings. Parse them at the edge, not in every component.
  • structuredClone is the default for deep copies today. Reach for a hand-written clone only when you need to keep prototypes or copy functions.

The exercises

  1. pick and omit: own keys only, and "missing" versus "undefined".
  2. Word counts: a dictionary that survives constructor and __proto__.
  3. get by path: read 'orders[0].items[2].sku' safely.
  4. Inheritance without class: wire constructor functions and prototypes by hand.
  5. Object diff: what changed between two versions of a record.
  6. Deep merge: layered config without mutation and without prototype pollution.
  7. Deep equal: compare Dates, Maps, Sets, NaN and cycles.
  8. 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