Object-Oriented JavaScript

Objects & OOP

In JavaScript, almost everything is an object. Master object literals, ES6 classes, inheritance, encapsulation, and composition patterns — the foundation of scalable, maintainable applications.

How do objects work in JavaScript?

An object is a collection of key–value pairs (properties), written as { name: "Ada", age: 36 }. Read and write properties with dot notation (user.name) or brackets (user["name"], needed for dynamic keys). Functions stored on objects are methods. Object.keys, Object.values and Object.entries turn an object into arrays you can loop over.

const user = {
  name: "Ada",
  skills: ["math", "code"],
  greet() { return `Hi, I'm ${this.name}`; },
};
user.age = 36;                       // add
delete user.age;                     // remove
const key = "name";
user[key];                           // dynamic access
const copy = { ...user, name: "Grace" };   // shallow copy + override

What is an Object?

An object is a collection of key–value pairs where keys are strings (or Symbols) and values can be anything — primitives, other objects, or functions (called methods). Objects model real-world entities and group related data and behaviour together.

// Object literal syntax
const car = {
make: 'Toyota',
year: 2023,
start() { /* method */ }
}

The 4 OOP Principles

Encapsulation

Bundle data and methods; hide implementation using private fields (#) or closures.

Inheritance

Build new classes on existing ones with extends. Re-use and specialise behaviour.

Polymorphism

Different objects respond to the same method call in their own way (override).

Abstraction

Expose only what's necessary; hide complexity behind a clean public interface.

Object Syntax Reference

FeatureSyntaxExample / Notes
Literal{ key: value }const p = { name: 'Alice', age: 30 }
Dot accessobj.keyp.name → 'Alice'
Bracket accessobj['key'] or obj[var]Useful for dynamic/computed keys
Method shorthand{ fn() {} }Preferred over { fn: function() {} }
Computed key{ [expr]: value }const k = 'x'; { [k]: 1 } → { x: 1 }
Getterget prop() { return ... }Accessed like a property: obj.prop
Setterset prop(v) { this._p = v }Called on assignment: obj.prop = val
Spread clone{ ...obj }Shallow copy — nested refs still shared
Object.keys()Object.keys(obj)Array of own enumerable keys
Object.entries()Object.entries(obj)Array of [key, value] pairs
Object.freeze()Object.freeze(obj)Makes all properties non-writable
Object.assign()Object.assign(target, ...srcs)Merge sources into target (mutates!)
definePropertyObject.defineProperty(obj, key, desc)Set writable / enumerable / configurable

Try It — Object Fundamentals

Explore object creation, property access, methods, getters/setters, and built-in helpers. Switch to the JS tab to edit code and the preview shows live results.

Code Editor

<pre id="out"></pre>

Preview

Class Anatomy

class Vehicle {
#speed = 0; // private field
brand; // public field

constructor(brand) {
this.brand = brand;
}

accelerate(by) { // method
this.#speed += by;
}

get speed() { return this.#speed; }

static compare(a, b) { // static
return a.speed - b.speed;
}
}

Inheritance with extends

class Car extends Vehicle {
#doors;

constructor(brand, doors) {
// MUST call super() before this!
super(brand);
this.#doors = doors;
}

// Override parent method
accelerate(by) {
super.accelerate(by * 1.1); // call parent
}

get info() {
return `${this.brand} (${this.#doors} doors)`;
}
}

Always call super() before using this in a derived constructor. Use super.method() to invoke the parent's version from an override.

Try It — Classes & OOP

Experiment with classes, private fields, inheritance, polymorphism, static methods, and mixins.

Code Editor

<pre id="out"></pre>

Preview

Encapsulation — Private Fields

✗Without Encapsulation

class User {
constructor(name, pass) {
this.name = name;
this.password = pass; // exposed!
}
}
const u = new User('Alice','secret');
console.log(u.password); // 'secret'
u.password = 'hacked!';

✓With Private Fields (#)

class User {
#password;
constructor(name, pass) {
this.name = name;
this.#password = pass;
}
checkPw(p) { return p === this.#password; }
}
const u = new User('Alice','secret');
console.log(u.checkPw('secret')); // true
// u.#password → SyntaxError ✅

Factory Function Pattern

A factory function creates and returns an object without new. True privacy through closures, flexible creation logic, no inheritance needed.

function createCounter(start = 0) {
// Private via closure:
let count = start;
return {
increment: () => ++count,
decrement: () => --count,
reset: () => (count = start),
value: () => count,
}
}

const c = createCounter(10);
c.increment(); c.increment();
console.log(c.value()); // 12
// c.count → undefined (truly private)

Composition over Inheritance

Compose small, focused behaviours rather than building deep class hierarchies. Avoids the "fragile base class" problem and keeps code easy to change.

// Behaviours as functions:
const canSwim = o => ({ swim() { return `${o.name} swims`; }});
const canFly = o => ({ fly() { return `${o.name} flies`; }});
const canQuack = o => ({ quack() { return 'Quack!'; }});

function createDuck(name) {
const duck = { name };
return Object.assign(duck,
canSwim(duck), canFly(duck), canQuack(duck));
}

const d = createDuck('Donald');
console.log(d.swim()); // Donald swims
console.log(d.fly()); // Donald flies

Common Mistakes to Avoid

🔁

Mutating shared object references

✗const b = a; b.x = 99; // mutates a too!
✓const b = { ...a }; b.x = 99; // independent copy
🏗️

Deep inheritance chains

✗A → B → C → D → E (fragile, hard to change)
✓Compose small behaviours; keep hierarchy shallow
🔒

Exposing internal state directly

✗this.password = hash; // anyone can read/write
✓Use #privateField for truly private data
⚡

Arrow functions as class methods

✗{ greet: () => this.name } // 'this' = outer scope
✓{ greet() { return this.name; } } // correct 'this'
📦

Modifying frozen objects

✗frozen.x = 99; // silently fails (strict: throws)
✓Return new object: { ...frozen, x: 99 }
🔗

Forgetting super() in subclass

✗constructor() { this.x = 1; } // ReferenceError!
✓Always call super() before using 'this' in extends

Best Practices

Prefer composition over deep inheritance

Mixins and factory functions scale better than class hierarchies

Use # private fields for sensitive data

True privacy — not just convention like _password

Avoid mutating arguments or shared references

Return new objects; use { ...obj } to clone

Keep classes focused (Single Responsibility)

One class, one job — split if it gets too large

Prefer factory functions for simple objects

Simpler than classes when inheritance is not needed

Use regular methods, not arrow functions

Arrow functions bind outer 'this' — breaks class methods

Class vs Factory vs Object Literal

Object LiteralFactory FunctionClass
Use whenSingle unique objectMultiple instances, no inheritanceMultiple instances + inheritance
InheritanceNoVia composition / mixinsYes — extends
Private dataClosure (limited)✅ Closure-based✅ # private fields
this keywordYesUsually avoidedYes — required
instanceofNoNoYes
BoilerplateMinimalLowMedium
PerformanceFastest for one-offEach instance has own methodsShared prototype methods

Objects and OOP — step by step

1 / 4
1

Object creation patterns

Object literal {} is the simplest form. Object.create(proto) creates an object with an explicit prototype. Constructor functions with new are the classic OOP pattern. ES6 class syntax is syntactic sugar over constructor functions and prototype assignment. Factory functions return plain objects — no new, no this, no prototype chain.

1 of 4
🔍Prefer Object.keys over for...in for own properties
for...in iterates over ALL enumerable properties including inherited ones. Object.keys() returns only own enumerable properties as an array. Object.entries() gives [key, value] pairs. Object.fromEntries() converts them back to an object. For most iteration needs, Object.keys/values/entries is safer and more predictable than for...in.

🎯 Quick Check

What does Object.freeze(obj) do?

Objects & OOP — Mastered! 🎉

Next: explore how the prototype chain powers inheritance under the hood.

JavaScript Objects: summary

Key points

  • Shorthand: { name } means { name: name }.
  • Objects are compared by reference: two separate {} are never ===.
  • The spread syntax { ...obj } makes a shallow copy; use structuredClone(obj) for a deep copy.
  • Object.freeze(obj) prevents changes (shallowly).

Frequently asked questions

›How do I loop through an object?

Use for (const [key, value] of Object.entries(obj)) { … }.

›How do I check if a property exists?

Use "key" in obj (includes inherited properties) or Object.hasOwn(obj, "key") (own properties only).