Updated Nov 29, 2026

04 - Objects and Prototypes

📋 Jump to Takeaways

🎁 JavaScript objects aren't structs and they aren't maps. They're something in between, with an invisible chain of inherited properties that most languages don't have. Understanding it explains half the "weird" JavaScript behavior you'll encounter.

Objects are dynamic bags of key-value pairs. Not structs (no fixed shape at runtime). Not plain dictionaries either (they have a prototype chain that can inject properties you didn't put there). Coming from Go, think of them as maps with superpowers and some footguns.

Object Basics

Create objects with literal syntax. Properties can be added, changed, or deleted at any time.

const user = {
  name: "alice",
  age: 30,
  active: true,
};

console.log(user.name);    // "alice"
console.log(user["age"]);  // 30

user.email = "[email protected]"; // TS error: Property 'email' does not exist

// To allow dynamic properties, type the object with an index signature:
const flexUser: { name: string; age: number; [key: string]: unknown } = {
  name: "alice",
  age: 30,
};
flexUser.email = "[email protected]"; // OK

Dot notation for known keys. Bracket notation for dynamic keys.

const field = "name";
console.log(user[field]); // "alice"

// Computed property names
const key = "status";
const config = {
  [key]: "active",
  [`${key}Code`]: 200,
};
console.log(config); // { status: "active", statusCode: 200 }

In Go, you'd use a struct for known shapes and map[string]any for dynamic data. Here, one construct handles both.

Destructuring

Destructuring pulls values out of objects into variables. You'll see this in every TypeScript codebase.

const user = { name: "alice", age: 30, role: "admin" };

const { name, age } = user;
console.log(name); // "alice"
console.log(age);  // 30

// Rename during destructuring
const { name: userName, role: userRole } = user;
console.log(userName); // "alice"
console.log(userRole); // "admin"

// Default values
const { name: n, email = "none" } = user;
console.log(email); // "none"

Nested destructuring:

const response = {
  data: {
    user: {
      name: "alice",
      address: { city: "portland" },
    },
  },
  status: 200,
};

const {
  data: {
    user: {
      name,
      address: { city },
    },
  },
} = response;

console.log(name); // "alice"
console.log(city); // "portland"

Function parameters use destructuring constantly:

interface Config {
  host: string;
  port: number;
  ssl?: boolean;
}

function connect({ host, port, ssl = false }: Config): void {
  console.log(`Connecting to ${host}:${port} (ssl: ${ssl})`);
}

connect({ host: "localhost", port: 5432 });
// Connecting to localhost:5432 (ssl: false)

In Go, you pass a struct and access fields inside the function. In TypeScript, you destructure in the parameter list and get named variables right away.

Spread Operator

The spread operator (...) shallow-copies and merges objects. Creates a new object every time.

const defaults = { theme: "dark", lang: "en", debug: false };
const userPrefs = { theme: "light", debug: true };

const config = { ...defaults, ...userPrefs };
console.log(config);
// { theme: "light", lang: "en", debug: true }

Later spreads overwrite earlier ones. This is how you merge configs, apply patches, and create modified copies.

// Immutable update pattern
const user = { name: "alice", age: 30, role: "user" };
const promoted = { ...user, role: "admin" };

console.log(user.role);     // "user" (original unchanged)
console.log(promoted.role); // "admin"

Spread is shallow. Nested objects are still references.

const original = { name: "alice", address: { city: "portland" } };
const copy = { ...original };

copy.address.city = "seattle";
console.log(original.address.city); // "seattle" (same reference!)

For deep copies, use structuredClone:

const deep = structuredClone(original);
deep.address.city = "denver";
console.log(original.address.city); // "seattle" (unaffected)

Prototypal Inheritance

Every object has an internal link to another object called its prototype. When you access a property that doesn't exist on the object, the engine walks up the prototype chain looking for it.

const animal = {
  speak() {
    return `${this.name} makes a sound`;
  },
};

const dog = Object.create(animal);
dog.name = "Rex";

console.log(dog.speak());  // "Rex makes a sound"
console.log(dog.hasOwnProperty("name"));  // true
console.log(dog.hasOwnProperty("speak")); // false (it's on the prototype)

console.log(Object.getPrototypeOf(dog) === animal); // true

The chain ends at Object.prototype, which has methods like hasOwnProperty, toString, and valueOf. Every object gets these for free.

const obj = { x: 1 };
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
console.log(Object.getPrototypeOf(Object.prototype));          // null (end of chain)

Classes Are Syntactic Sugar

ES6 classes look like Java/Go structs with methods. They're really just constructor functions with prototypes.

class User {
  name: string;
  age: number;

  constructor(name: string, age: number) {
    this.name = name;
    this.age = age;
  }

  greet(): string {
    return `hi, i'm ${this.name}`;
  }
}

const u = new User("alice", 30);
console.log(u.greet()); // "hi, i'm alice"

The equivalent without classes (JavaScript pattern — won't type-check in TypeScript without workarounds):

// This is how classes compile to plain JS — constructor function + prototype.
// TypeScript doesn't allow `new` on regular functions; the `as any` cast is needed here.
function User(this: any, name: string, age: number) {
  this.name = name;
  this.age = age;
}

User.prototype.greet = function (): string {
  return `hi, i'm ${this.name}`;
};

const u = new (User as any)("alice", 30);
console.log(u.greet()); // "hi, i'm alice"

Same result. The class syntax is what you should use in TypeScript, but knowing this pattern helps when reading older JavaScript codebases.

Class inheritance:

class Admin extends User {
  permissions: string[];

  constructor(name: string, age: number, permissions: string[]) {
    super(name, age);
    this.permissions = permissions;
  }

  canAccess(resource: string): boolean {
    return this.permissions.includes(resource);
  }
}

const admin = new Admin("bob", 25, ["users", "settings"]);
console.log(admin.greet());              // "hi, i'm bob"
console.log(admin.canAccess("users"));   // true

Object Utility Methods

Three methods you'll use constantly:

const config = { host: "localhost", port: 5432, ssl: false };

// Keys
console.log(Object.keys(config));
// ["host", "port", "ssl"]

// Entries (key-value pairs)
console.log(Object.entries(config));
// [["host", "localhost"], ["port", 5432], ["ssl", false]]

// Iterate with entries
for (const [key, value] of Object.entries(config)) {
  console.log(`${key} = ${value}`);
}
// host = localhost
// port = 5432
// ssl = false

Object.freeze makes an object immutable (shallow):

const frozen = Object.freeze({ host: "localhost", port: 5432 });
frozen.port = 3000; // TypeError in strict mode (all TS modules are strict)
console.log(frozen.port); // 5432

Object.assign merges objects (mutates the target):

const target = { a: 1 };
Object.assign(target, { b: 2 }, { c: 3 });
console.log(target); // { a: 1, b: 2, c: 3 }

Use spread over Object.assign when you want a new object. Use Object.assign when you intentionally want to mutate.

Composition Over Inheritance

In Go, you compose with struct embedding. Deep inheritance hierarchies are an anti-pattern here. Use plain objects and composition instead.

// Instead of class hierarchies, compose behavior
interface Logger {
  log(msg: string): void;
}

interface Validator {
  validate(data: unknown): boolean;
}

function createService(logger: Logger, validator: Validator) {
  return {
    process(data: unknown) {
      if (!validator.validate(data)) {
        logger.log("invalid data");
        return;
      }
      logger.log("processing...");
    },
  };
}

const service = createService(
  { log: (msg) => console.log(`[SVC] ${msg}`) },
  { validate: (data) => data !== null },
);

service.process("hello"); // [SVC] processing...
service.process(null);    // [SVC] invalid data

No classes. No extends. Just functions and interfaces. Most modern TypeScript codebases work this way. You'll see classes in libraries (ORMs, frameworks), but application code leans toward plain objects and factory functions.

Key Takeaways

  • JS objects are dynamic key-value bags with a prototype chain. Not structs, not plain dicts.
  • Destructuring extracts values from objects into variables. Used everywhere, especially in function parameters.
  • Spread (...) creates shallow copies and merges objects. Use structuredClone for deep copies.
  • Every object has a prototype chain. Property lookups walk up the chain until they find the property or hit null.
  • Classes are syntactic sugar over constructor functions and prototypes. Same mechanism underneath.
  • Object.keys, Object.entries, Object.freeze are your daily tools for working with objects.
  • Prefer composition (plain objects, factory functions, interfaces) over class inheritance. Same philosophy as Go's embedding.

🎁 Go interfaces match by method signatures. TypeScript doesn't care about method signatures alone — it matches by shape, and any object with the right property names and types is compatible. What does that mean for a type system that never makes you write implements?

📝 Ready to test your knowledge?

Answer the quiz below to mark this lesson complete.

Spot something off? Report an issue