# JavaScript Research β€” Index

> Comprehensive research on JavaScript features, patterns, Web APIs, and internals. Compiled May 2025.

---

## Documents

### 1. [JavaScript_Modern_Features.md](JavaScript_Modern_Features.md)
ES2020 through ES2025 features with practical examples.

**Topics:**
- **ES2020:** `?.` optional chaining, `??` nullish coalescing, `globalThis`, `Promise.allSettled()`, `BigInt`
- **ES2021:** `replaceAll()`, `Promise.any()`, `??=`/`||=`/`&&=`, `WeakRef`, `FinalizationRegistry`
- **ES2022:** Top-level `await`, `.at(-1)`, private fields `#`, `Object.hasOwn()`
- **ES2023:** `.toSorted()`/`.toReversed()`/`.toSpliced()`/`.with()`, `.findLast()`/`.findLastIndex()`
- **ES2024:** `Promise.withResolvers()`, `RegExp /d` flag, `RegExp /v` flag
- **ES2025:** `Object.groupBy()`, `Set.union()`/`.intersection()`/`.difference()`, `String.isWellFormed()`, `ArrayBuffer.transfer()`
- **Modules:** Dynamic `import()`, import assertions, top-level await

### 2. [JavaScript_Advanced_Patterns.md](JavaScript_Advanced_Patterns.md)
Closures, prototypes, iterators, generators, proxies, and design patterns.

**Topics:**
- **Closures:** Function factories, memoization, event handler cleanup
- **Prototypes:** Prototype chain, `Object.create()`, manual manipulation
- **Iterators:** Custom `[Symbol.iterator]()`, generators (`function*`), `yield*`, sending values
- **Proxies:** Validation proxy, reactive proxy (Vue-style), lazy loading proxy
- **Design Patterns:** Singleton, Observer/EventEmitter, Module (IIFE), Factory, Decorator
- **Gotchas:** `this` context, type coercion, hoisting, `for...in` vs `for...of`, event loop (microtasks vs macrotasks)

### 3. [JavaScript_Web_APIs.md](JavaScript_Web_APIs.md)
Browser APIs for building modern web applications.

**Topics:**
- **Fetch API:** Error handling, timeouts, request/response cloning, AbortController
- **Streams API:** Readable/Writable/Transform streams, pipeline, compression
- **Service Workers:** Lifecycle, cache-first strategy, push notifications, background sync
- **WebSockets:** Real-time communication, reconnection with exponential backoff
- **Web Workers:** Dedicated worker, shared worker, module workers
- **Storage:** localStorage, sessionStorage, IndexedDB (full class), Cache API
- **Media:** MediaDevices (camera/mic), MediaRecorder, Web Audio API, MSE
- **Performance:** PerformanceObserver (LCP/CLS/FID), User Timing API
- **Files:** File System Access API, Drag & Drop
- **Other:** Navigation API, Credentials API, Web Crypto API

### 4. [JavaScript_Performance_Internals.md](JavaScript_Performance_Internals.md)
V8 engine internals, JIT compilation, garbage collection, and optimization.

**Topics:**
- **V8 Architecture:** Ignition (interpreter) β†’ TurboFan (JIT compiler), deoptimization
- **Hidden Classes (Maps):** Object shape optimization, consistent property order
- **Inline Caching:** Monomorphic vs polymorphic vs megamorphic
- **Garbage Collection:** Two-space GC (Young/Old), Scavenge vs Mark-Sweep-Compact, memory leak patterns
- **Anti-Patterns:** Blocking main thread, string concatenation, DOM manipulation, expensive queries
- **Array Performance:** `.map()` vs `forEach()` vs `for` loop, Object vs Map, Set vs Array
- **Debounce/Throttle:** `debounce()`, `throttle()`, `rAFThrottle()`
- **Lazy Loading:** Module loading, IntersectionObserver, lazy component rendering
- **Memory Optimization:** Object pooling, WeakMap caching, transferable objects
- **V8-Specific:** Smi range, inline optimizations, Typed Arrays, tree shaking

---

## Key Things I Learned

1. **`?.` optional chaining** short-circuits on null/undefined β€” `user?.address?.city` is cleaner than any guard clause.

2. **`??` nullish coalescing** only treats `null`/`undefined` as fallback β€” unlike `||` which also catches `0`, `""`, `false`.

3. **`Promise.any()`** returns the first *fulfilled* promise β€” different from `Promise.race()` which returns first settled (even if rejected).

4. **`Promise.withResolvers()`** (ES2024) cleanly separates a promise from its resolve/reject functions β€” great for event-to-promise bridges.

5. **`BigInt`** is a separate type β€” can't mix with `Number` without explicit conversion.

6. **Top-level `await`** works in ES modules β€” no IIFE wrapper needed.

7. **`.at(-1)`** works on arrays, strings, and typed arrays β€” native negative indexing.

8. **`.toSorted()`/`.toReversed()`/`.with()`** are non-mutating array operations β€” functional programming in native JS.

9. **`Set` operations** (ES2025): `.union()`, `.intersection()`, `.difference()`, `.symmetricDifference()` β€” no more lodash for set math.

10. **`Object.groupBy()`** (ES2025) groups arrays into Maps β€” replaces manual reduce patterns.

11. **Generators (`function*`)** produce lazy sequences β€” infinite sequences without memory issues.

12. **Proxies** intercept ALL object operations β€” validation, reactive state, lazy loading, virtual properties.

13. **Hidden classes (Maps)** in V8 mean object property *order* matters for performance β€” always add properties in the same order.

14. **Deoptimization** happens when assumptions break β€” passing a string to a function optimized for numbers forces fallback to interpreter.

15. **V8's two-space GC**: Young generation (scavenge, fast) vs Old generation (mark-sweep, slower). Objects promote after 1-2 GC cycles.

16. **Smi (small integers)** are 31-bit integers stored directly β€” faster than doubles or BigInts.

17. **Typed Arrays** are 5-10x faster for numerical computation than regular arrays β€” contiguous native memory, no object overhead.

18. **Inline caching** in V8: monomorphic (one shape) β†’ fastest, polymorphic (few shapes) β†’ fast, megamorphic (many shapes) β†’ slow.

19. **WeakMap** is perfect for caching tied to object lifecycle β€” entries auto-GC when key is no longer referenced.

20. **`rAFThrottle()`** syncs scroll/resize handlers to display refresh rate β€” no wasted frames.

21. **Service Workers** have a distinct lifecycle: install β†’ activate β†’ control pages β†’ handle events.

22. **Streams API** enables processing data as it arrives β€” no need to wait for entire response.

23. **File System Access API** lets browsers read/write files directly — no more input→blob→download workaround.

24. **`Object.hasOwn()`** is safer than `hasOwnProperty.call()` β€” works with null-prototype objects.

25. **`String.replaceAll()`** replaces all occurrences without regex β€” no more `/g` flag.

26. **Memory leak patterns:** forgotten timers, detached DOM elements, closures holding large data, implicit globals.

27. **DocumentFragment** batches DOM insertions β€” single reflow instead of N reflows.

28. **`Promise.allSettled()`** collects all results (success and failure) β€” vs `Promise.all()` which fails fast.

29. **`globalThis`** is universal β€” works in browser, Node.js, and Web Workers.

30. **Event Loop:** microtasks (Promise callbacks, queueMicrotask) always run before macrotasks (setTimeout, setInterval).

---

## Quick Reference: JavaScript ES Timeline

| Year | Key Features |
|------|-------------|
| **ES2020** | `?.`, `??`, `globalThis`, `Promise.allSettled`, `BigInt` |
| **ES2021** | `replaceAll()`, `Promise.any()`, `??=`/`||=`, `WeakRef` |
| **ES2022** | Top-level `await`, `.at()`, private fields `#`, `Object.hasOwn()` |
| **ES2023** | `.toSorted()`, `.with()`, `.findLast()`, hashbang |
| **ES2024** | `Promise.withResolvers()`, `RegExp /d`, `RegExp /v` |
| **ES2025** | `Object.groupBy()`, `Set.union()`, `String.isWellFormed()`, `ArrayBuffer.transfer()` |

---

## Quick Reference: API Selection

| Need | API |
|------|-----|
| HTTP requests | Fetch + AbortController |
| Real-time | WebSockets with reconnection |
| Background work | Web Workers |
| Offline | Service Workers + Cache API |
| Large data storage | IndexedDB |
| Simple storage | localStorage (JSON.stringify) |
| Camera/Mic | MediaDevices |
| Audio processing | Web Audio API |
| Performance metrics | PerformanceObserver |
| File access | File System Access API |
| Encryption | Web Crypto API |
| Debounce input | `debounce()` + Fetch |
| Throttle scroll | `rAFThrottle()` |
| Lazy load | `loading="lazy"` + IntersectionObserver |

---

## Quick Reference: Performance Tips

| Issue | Solution |
|-------|----------|
| Slow lookups | Use `Map`/`Set` instead of `Object`/`Array` |
| Memory leak | Use `WeakMap` for caches, remove listeners |
| UI jank | `transform`/`opacity` only for animations |
| Main thread blocked | Web Workers or chunked processing |
| Large DOM updates | `DocumentFragment` or `innerHTML` |
| Scroll/resize spam | `rAFThrottle()` or `throttle()` |
| Input spam | `debounce()` |
| Large images | `loading="lazy"`, srcset, WebP/AVIF |
| Slow computation | Typed Arrays, keep ints as Smi |
| Bundle too large | Tree shaking, dynamic `import()` |
| GC pauses | Object pooling, transfer objects |
| Deoptimization | Consistent object shapes and types |