const cache = new WeakMap();
function process(data, transform = (x) => x * 2) {
if (cache.has(transform)) {
console.log('cache hit');
return cache.get(transform)(data);
}
console.log('cache miss');
cache.set(transform, transform);
return transform(data);
}
process(5); // cache miss
process(5); // cache miss again ā different transform reference!
process(5); // always miss// Define the default OUTSIDE the function ā same reference always
const defaultTransform = (x) => x * 2;
const cache = new WeakMap();
function process(data, transform = defaultTransform) {
if (cache.has(transform)) {
console.log('cache hit');
return cache.get(transform)(data);
}
console.log('cache miss');
cache.set(transform, transform);
return transform(data);
}
process(5); // cache miss
process(5); // cache hit ā same defaultTransform reference
process(5, x => x * 3); // cache miss (new function provided)Bug: Default parameter (x) => x * 2 creates a NEW function object every time process() is called without a transform. Each call has a unique reference ā WeakMap never finds it.
Explanation: Default parameter expressions are evaluated fresh on each call ā each evaluation creates a new function object with a new reference. Moving the default outside ensures a stable reference across calls.
Key Insight: Default parameter expressions are re-evaluated on every call. If identity (===) matters (for caching, WeakMap keys, memoization), define constants outside the function.