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 + overrideWhat 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.
The 4 OOP Principles
Bundle data and methods; hide implementation using private fields (#) or closures.
Build new classes on existing ones with extends. Re-use and specialise behaviour.
Different objects respond to the same method call in their own way (override).
Expose only what's necessary; hide complexity behind a clean public interface.
Object Syntax Reference
| Feature | Syntax | Example / Notes |
|---|---|---|
| Literal | { key: value } | const p = { name: 'Alice', age: 30 } |
| Dot access | obj.key | p.name → 'Alice' |
| Bracket access | obj['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 } |
| Getter | get prop() { return ... } | Accessed like a property: obj.prop |
| Setter | set 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!) |
| defineProperty | Object.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
Inheritance with extends
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
✓With Private Fields (#)
Factory Function Pattern
A factory function creates and returns an object without new. True privacy through closures, flexible creation logic, no inheritance needed.
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.
Common Mistakes to Avoid
Mutating shared object references
const b = a; b.x = 99; // mutates a too!const b = { ...a }; b.x = 99; // independent copyDeep inheritance chains
A → B → C → D → E (fragile, hard to change)Compose small behaviours; keep hierarchy shallowExposing internal state directly
this.password = hash; // anyone can read/writeUse #privateField for truly private dataArrow 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 extendsBest 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 Literal | Factory Function | Class | |
|---|---|---|---|
| Use when | Single unique object | Multiple instances, no inheritance | Multiple instances + inheritance |
| Inheritance | No | Via composition / mixins | Yes — extends |
| Private data | Closure (limited) | ✅ Closure-based | ✅ # private fields |
| this keyword | Yes | Usually avoided | Yes — required |
| instanceof | No | No | Yes |
| Boilerplate | Minimal | Low | Medium |
| Performance | Fastest for one-off | Each instance has own methods | Shared prototype methods |
Objects and OOP — step by step
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.
🎯 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; usestructuredClone(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).