objects
Objects in JavaScript
Property descriptors, prototype links, shallow vs deep copying, and immutability controls.
The High-Security Vault System
Objects are collections of key-value pairs stored in the Memory Heap. Variables storing objects hold memory references (pointers), not the actual data itself.
Reference Semantics in Memory Heap
When assigning `objB = objA`, both variables point to the exact same memory address on the heap. Mutating `objB` mutates `objA`.
Shallow vs Deep Copying
Shallow copies (`{ ...obj }`, `Object.assign()`) clone top-level properties but copy references for nested objects. Deep copies (`structuredClone()`, recursive clones) duplicate every nested object independently.
Object Traversal Utilities
`Object.keys()`, `Object.values()`, and `Object.entries()` return arrays of enumerable own properties, ideal for functional pipelines.
Immutability Levels
`Object.preventExtensions()`: no new properties. `Object.seal()`: no new/deleted properties. `Object.freeze()`: no new, deleted, or modified properties (shallow).
Deep copying with structuredClone vs shallow copy and Object.freeze:
const hero = {
name: "Spider-Man",
details: { city: "Queens", suit: "Spandex" }
};
// 1. Shallow copy pitfall
const shallow = { ...hero };
shallow.details.city = "Brooklyn";
console.log("Original affected by shallow:", hero.details.city); // Brooklyn!
// 2. Modern Deep Copy
const deep = structuredClone(hero);
deep.details.city = "Manhattan";
console.log("Original safe with deep:", hero.details.city); // Brooklyn (unchanged by deep)
// 3. Object.freeze (Shallow immutability)
const frozen = Object.freeze({ appName: "ConsistCode" });
// frozen.appName = "Hacked"; // In strict mode throws TypeError
console.log("Frozen appName:", frozen.appName);
Original affected by shallow: Brooklyn
Original safe with deep: Brooklyn
Frozen appName: ConsistCode
Object.freeze is Shallow Only
The Risk: `Object.freeze(obj)` only freezes top-level keys. Nested objects like `obj.nested.key = "new"` can still be freely mutated.
The Fix: Use a recursive `deepFreeze()` helper if full immutability across all nested levels is required.
Equality Checking Objects by Reference
The Risk: `{ a: 1 } === { a: 1 }` evaluates to `false` because they occupy different addresses in heap memory.
The Fix: For structural equality, perform deep comparisons (e.g., recursive checks or lodash `isEqual`).
- ✓ Objects are reference types stored in the Heap.
- ✓ Shallow copy (`{ ...obj }`) does NOT clone nested objects.
- ✓ Use native `structuredClone(obj)` for modern deep copies.
- ✓ `Object.freeze()` is shallow; nested objects remain mutable unless deep-frozen.
- ✓ Comparing two distinct objects with `===` checks reference equality, not structural values.