Chapter 4 of 12
4.1 Objects & Property Descriptors
Objects in JS are key-value stores. Every property on an object is governed by property descriptors controlling mutability, enumerability, and configurability.
Property Descriptors & Deep Cloningjavascript
const config = {};
Object.defineProperty(config, 'API_KEY', {
value: 'secret_12345',
writable: false, // Cannot be overwritten
enumerable: false, // Hidden from Object.keys() / for...in
configurable: false // Cannot be deleted
});
// Deep Copying with structuredClone (Native ES2022)
const original = { user: { name: 'Alice' }, date: new Date() };
const deepCopy = structuredClone(original);
deepCopy.user.name = 'Bob'; // original.user.name remains 'Alice'!4.2 Arrays & Modern Functional Methods
JavaScript Arrays offer functional non-mutating methods and modern grouping capabilities.
Array Transmutation & Object.groupByjavascript
const inventory = [
{ name: 'Apples', category: 'Fruit', qty: 10 },
{ name: 'Carrots', category: 'Vegetable', qty: 5 },
{ name: 'Bananas', category: 'Fruit', qty: 20 }
];
// Object.groupBy (ES2024)
const grouped = Object.groupBy(inventory, item => item.category);
// Output: { Fruit: [...], Vegetable: [...] }
// Array.prototype.reduce
const totalQty = inventory.reduce((sum, item) => sum + item.qty, 0); // 354.3 Keyed Collections: Map, Set, WeakMap, WeakSet
Map maintains insertion order and supports any key type (including objects). WeakMap keys are garbage-collectable, making them ideal for private metadata storage.
Map vs WeakMapjavascript
// Set Operations (ES2024 Native Set Methods)
const setA = new Set([1, 2, 3]);
const setB = new Set([3, 4, 5]);
const intersection = setA.intersection(setB); // Set { 3 }
// WeakMap Garbage Collection
let domNode = document.createElement('div');
const metadata = new WeakMap();
metadata.set(domNode, { clicked: 4 });
domNode = null; // Memory released automatically! WeakMap entry removed.