Notes · JavaScript
Advanced JavaScript
Memory leaks · Debounce and throttle · Functional programming
On this page · 7 sections
Overview
Keeping memory flat in long sessions, limiting how often expensive handlers run, and writing small pure functions.
Key concepts
- Memory leak: Memory held by objects you no longer need, but that something still points to (a global, a timer, a listener, a closure).
- Garbage collection in V8: New objects go to a small “young” area that is cleaned often and fast. Objects that survive move to the “old” area, which is cleaned with mark-sweep and compaction. Much of the work runs in the background. V8 frees what is unreachable, so cycles are not a problem.
- Debounce: Run the function only after calls stop for N ms. Example: search box.
- Throttle: Run the function at most once every N ms. Example: scroll handler. For visual updates,
requestAnimationFrameoften works better. - Higher-order function: A function that takes or returns a function. Examples:
map,filter,reduce,debounce. - Pure function: Same input gives the same output, and nothing else changes.
- Currying: Turn
f(a, b)intof(a)(b). - Memoization: Cache results of a pure function by its arguments.
- Composition:
compose(f, g)(x)meansf(g(x)). - Factory function vs function factory: The first returns an object (
createUser(name)). The second returns a function (makeMultiplier(2)). - Event delegation: One listener on a parent handles events from all its children, using
event.target.
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
function throttle(fn, interval) {
let last = 0;
return function (...args) {
const now = Date.now();
if (now - last >= interval) {
last = now;
fn.apply(this, args);
}
};
}
Real-world usage
- Search box: Debounce input (around 300 ms is common), so the API is called when the user pauses, not on every key.
- Infinite scroll: Throttle the scroll handler, or use
IntersectionObserverand skip the handler. - Finding leaks: In Chrome DevTools, take a heap snapshot, repeat an action a few times, take another, and compare. Growing counts and “Detached” DOM nodes point to the leak.
- Shaping API data: Turn a messy API response into a UI model with pure functions, without changing the original object.
Tradeoffs
map/filterchains vs aforloop: Chains are easier to read but create a new array at each step. In a measured hot loop, oneforloop can be faster.- Debounce vs throttle: Debounce can delay feedback for as long as events keep coming. Simple throttle (like the one above) can drop the last event.
- Immutability: Makes change detection and undo easy. Copying big objects on every change costs memory and GC time.
Object.freezeis shallow.
When not to use
- Copying large arrays on every change in hot code:
[...arr]andtoSorted()copy everything. If you own the data, sorting in place is fine. - Globals by accident: Assigning to an undeclared variable makes a global in sloppy mode. Top-level
varin a classic script becomes awindowproperty. Uselet/constand ES modules.
Interview focus
- App gets slower after navigating back and forth: Repeat the navigation, compare heap snapshots, then look for listeners, intervals, subscriptions, and caches that are never cleaned up.
- Write
debounce: See above. Mention keepingthisand arguments, leading vs trailing call, and acancelmethod. - Why purity matters in React/Redux: Reducers and render functions must be pure, so changes can be detected by reference and tested in isolation.
Common mistakes
- Listener not removed: A
windowlistener orsetIntervaladded in a component with nouseEffectcleanup. - Closure holding a DOM node: Keeps a removed element and its whole subtree in memory.
- Throttle interval too long: For example 1000 ms on drag-and-drop makes the UI feel stuck.
- Cache with no limit: A memoize
Mapgrows forever. Limit its size, or use aWeakMapwhen keys are objects.
From the notes repository on GitHub, synced Nov 17, 2026.Source ↗ (opens in a new tab)Report a mistake ↗ (opens in a new tab)