Advanced Closures
Published by Brayan K
A closure is a function bundled together with the variables from the scope where it was created, letting it remember and keep accessing those variables even after that outer function has finished running.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Give each asynchronous invocation the state it owns
A closure does not freeze the past. The practical question is which bindings should be shared across operations and which should belong to one invocation. This local loader shares a generation counter, but each load call owns its ticket. Only the most recently started call may publish a result.
function deferred() {
let resolve;
const promise = new Promise(done => { resolve = done; });
return { promise, resolve };
}
function createLatest(read) {
let generation = 0; // Shared by this loader's calls.
let value = "none";
return {
async load(id) {
const ticket = ++generation; // A separate binding for this invocation.
const result = await read(id);
if (ticket !== generation) return false;
value = result;
return true;
},
read: () => value
};
}
const first = deferred();
const second = deferred();
const loader = createLatest(id => id === "A" ? first.promise : second.promise);
const a = loader.load("A");
const b = loader.load("B");
second.resolve("new selection");
console.log(await b, loader.read());
first.resolve("old selection");
console.log(await a, loader.read());
// ✅ Expected output:
// true new selection
// false new selectionThe older operation still finishes; its value is simply not published. This is not cancellation, and it does not undo a server write. The fixture has no network. Closures and Scope owns live bindings and independent factory calls; Async/Await Architecture & Best Practices owns wider asynchronous coordination and error-display policies.
A shared label can change while one invocation is suspended
let resolveA;
const pendingA = new Promise(resolve => { resolveA = resolve; });
function createReader(read) {
let selected;
return async id => {
selected = id;
const value = await read(id);
return selected + ":" + value;
};
}
const reader = createReader(id => id === "A" ? pendingA : Promise.resolve("value-B"));
const first = reader("A");
console.log(await reader("B"));
resolveA("value-A");
console.log(await first);
// ✅ Expected output:
// B:value-B
// B:value-Aselected is intentionally shared, so the A invocation reads B after its await. If the label belongs to each call, use that call’s id parameter instead:
let resolveA;
const pendingA = new Promise(resolve => { resolveA = resolve; });
function createReader(read) {
return async id => {
const value = await read(id);
return id + ":" + value;
};
}
const reader = createReader(id => id === "A" ? pendingA : Promise.resolve("value-B"));
const first = reader("A");
console.log(await reader("B"));
resolveA("value-A");
console.log(await first);
// ✅ Expected output:
// B:value-B
// A:value-AThis fixes labeling, not which completion should update a shared screen. The generation policy in the worked example answers that separate question. A correct closure can still participate in a poorly specified concurrency policy.
A once wrapper must define success, failure and reentry
“Run once” is ambiguous. Does the first attempt count even if it throws? Is an undefined result a cached success? Can the operation call the wrapper again before it finishes? State those rules before choosing a boolean or cache variable.
function badOnce(fn) {
let result;
return () => {
if (result) return result;
result = fn();
return result;
};
}
let calls = 0;
const read = badOnce(() => { calls++; return 0; });
console.log(read(), read(), calls);
// ✅ Expected output:
// 0 0 2The following synchronous contract caches the first successful return, including zero or undefined. A thrown attempt leaves it available for retry. A running state rejects reentry instead of accidentally starting the same operation again. This is not a promise-aware once wrapper.
function onceSuccess(fn) {
"use strict";
let state = "empty";
let result;
return function (...args) {
if (state === "ready") return result;
if (state === "running") throw new Error("Reentrant call");
state = "running";
try {
result = fn.apply(this, args);
state = "ready";
return result;
} catch (error) {
state = "empty";
throw error;
}
};
}
let attempts = 0;
const read = onceSuccess(() => {
attempts++;
if (attempts === 1) throw new Error("First attempt failed");
return 0;
});
try { read(); } catch (error) { console.log(error.message); }
console.log(read(), read(), attempts);
let emptyCalls = 0;
const empty = onceSuccess(() => { emptyCalls++; return undefined; });
console.log(empty(), empty(), emptyCalls);
function strictReceiver() { "use strict"; return this; }
console.log("plain receiver", strictReceiver() === onceSuccess(strictReceiver)());
console.log("primitive receiver", strictReceiver.call(7) === onceSuccess(strictReceiver).call(7));
console.log("null receiver", strictReceiver.call(null) === onceSuccess(strictReceiver).call(null));
// ✅ Expected output:
// First attempt failed
// 0 0 2
// undefined undefined 1
// plain receiver true
// primitive receiver true
// null receiver truefunction onceSuccess(fn) {
"use strict";
let state = "empty";
let result;
return function (...args) {
if (state === "ready") return result;
if (state === "running") throw new Error("Reentrant call");
state = "running";
try {
result = fn.apply(this, args);
state = "ready";
return result;
} catch (error) {
state = "empty";
throw error;
}
};
}
let read;
read = onceSuccess(() => read());
read();
// ✅ Expected error:
// Error: Reentrant callThe strict factory preserves undefined, null and primitive receivers in its ordinary wrapper. Only the first successful call’s receiver and arguments affect the cached result. Later calls with different arguments still receive that same result. This is a one-time initialization contract, not a general memoizer keyed by all arguments. Performance Optimization owns cache correctness and workload measurement.
Sharing pending work is different from caching a completed result
If repeated callers need the same pending operation, store and return its promise. Removing the entry after settlement allows a later call to start fresh work. The factory below partitions that pending state by key and by factory instance.
function sharePending(read) {
const pending = new Map();
return key => {
if (pending.has(key)) return pending.get(key);
const promise = Promise.resolve().then(() => read(key));
pending.set(key, promise);
const cleanup = () => {
if (pending.get(key) === promise) pending.delete(key);
};
promise.then(cleanup, cleanup);
return promise;
};
}
let calls = 0;
let finish;
const read = sharePending(() => {
calls++;
return new Promise(resolve => { finish = resolve; });
});
const first = read("A");
const second = read("A");
console.log(first === second);
await Promise.resolve();
console.log("calls", calls);
finish("ready");
console.log(await first, await second);
const later = read("A");
await Promise.resolve();
console.log(later === first, "calls", calls);
finish("fresh");
console.log(await later);
// ✅ Expected output:
// true
// calls 1
// ready ready
// false calls 2
// freshThe outer function is deliberately not async: callers receive the exact stored promise. An async wrapper that returns that promise adopts its outcome but creates another promise identity. This matters only when identity is part of your contract.
const original = Promise.resolve("ready");
function direct() { return original; }
async function wrapped() { return original; }
console.log(direct() === original);
console.log(wrapped() === original);
console.log(await direct(), await wrapped());
// ✅ Expected output:
// true
// false
// ready readyPromise.resolve().then defers the reader call and converts a synchronous reader throw into a rejection of the stored promise. Mastering Promises: Chaining, Error Flow & Patterns owns promise construction, adoption and handler ordering.
Cleanup must remove its own entry, not a replacement’s entry
A caller may deliberately forget a pending key so a new operation can start. Forgetting is not cancellation: the earlier promise can still finish. Its cleanup must check that it still owns the current entry before deleting it.
const pending = new Map();
const oldEntry = Promise.resolve("old");
const newEntry = Promise.resolve("new");
pending.set("A", oldEntry);
pending.set("A", newEntry);
if (pending.get("A") === oldEntry) pending.delete("A");
console.log(pending.get("A") === newEntry);
pending.delete("A");
console.log(pending.has("A"));
// ✅ Expected output:
// true
// falseThe identity check protects the replacement. The unconditional delete at the end shows what a careless old cleanup would remove. This is state ownership, not a claim that JavaScript statements run simultaneously.
Cleanup chains also need a rejection policy. finally returns a new promise; handling the original promise does not automatically handle that separate result. The example below observes both promises explicitly, avoiding an unhandled rejection while showing their outcomes.
const failure = new Error("Failed");
const original = Promise.reject(failure);
const cleaned = original.finally(() => {});
const outcomes = await Promise.allSettled([original, cleaned]);
console.log(original === cleaned);
console.log(outcomes.map(result => result.status).join(","));
console.log(outcomes[0].reason === failure, outcomes[1].reason === failure);
// ✅ Expected output:
// false
// rejected,rejected
// true trueThe pending-work helper uses then(cleanup, cleanup) with a cleanup function that does not throw. Both branches finish normally, while callers still receive the original promise and its original outcome. If cleanup itself can fail, that derived chain needs explicit handling too. Error Handling owns preserving failures when cleanup also fails.
Choose the factory’s owner and release policy
function sharePending(read) {
const pending = new Map();
return key => {
if (pending.has(key)) return pending.get(key);
const promise = Promise.resolve().then(() => read(key));
pending.set(key, promise);
const cleanup = () => { if (pending.get(key) === promise) pending.delete(key); };
promise.then(cleanup, cleanup);
return promise;
};
}
const first = sharePending(key => Promise.resolve("first:" + key));
const second = sharePending(key => Promise.resolve("second:" + key));
const a = first("same");
const b = second("same");
console.log(a === b);
console.log(await a, await b);
// ✅ Expected output:
// false
// first:same second:sameMoving pending outside the factory would make all factories share it and would require a broader key contract. A key must include the distinctions relevant to the underlying data. Building Custom APIs with Fetch & Async Logic owns authenticated client boundaries; this example makes no request and stores no credentials.
An operation that never settles can retain its pending entry. Removing an entry does not cancel the operation or prove that no other reference retains its data. AbortController & Cancelling Async Work owns cancellation signals; JavaScript Memory Management & Garbage Collection owns reachability and memory investigation.
Guided exercise: cache a successful undefined result
Finish this simpler synchronous once-success wrapper. Its contract excludes reentry, so a boolean is sufficient here. A thrown call must not set the ready flag.
function onceSuccess(fn) {
let ready = false;
let result;
return () => {
if (___) return result; // 👉 replace ___ with ready
result = ___(); // 👉 replace ___ with fn
ready = ___; // 👉 replace ___ with true
return result;
};
}
let calls = 0;
const read = onceSuccess(() => { calls++; return undefined; });
console.log(read(), read(), calls);
// ✅ Expected output:
// undefined undefined 1Independent brief: deduplicate pending reads without stale cleanup
Write createPendingReader(read). Return load(key), forget(key) and size(). String keys identify pending operations. load rejects non-string keys synchronously with TypeError("Key must be a string"). Calls for a currently pending key return the same promise. Invoke read(key) through a promise reaction so synchronous throws become rejections. Remove the pending entry on either outcome, but only if it still refers to that promise.
forget removes the current entry and returns whether one existed. It does not cancel the old operation. A new load may then install a replacement. size reports current entries. There is no completed-result cache. Check sharing, forgetting, an older completion after replacement, rejection and retry, a synchronous reader throw and invalid key input.
function createPendingReader(read) {
const pending = new Map();
return {
load(key) {
if (typeof key !== "string") throw new TypeError("Key must be a string");
if (pending.has(key)) return pending.get(key);
const promise = Promise.resolve().then(() => read(key));
pending.set(key, promise);
const cleanup = () => {
if (pending.get(key) === promise) pending.delete(key);
};
promise.then(cleanup, cleanup);
return promise;
},
forget: key => pending.delete(key),
size: () => pending.size
};
}
const operations = [];
const calls = [];
const reader = createPendingReader(key => {
calls.push(key);
return new Promise((resolve, reject) => operations.push({ resolve, reject }));
});
const first = reader.load("A");
console.log("shared", first === reader.load("A"));
await Promise.resolve();
console.log("calls", calls.join(","));
console.log("forgot", reader.forget("A"));
const replacement = reader.load("A");
await Promise.resolve();
operations[0].resolve("old");
console.log(await first);
console.log("replacement retained", reader.load("A") === replacement, reader.size());
operations[1].resolve("new");
console.log(await replacement, reader.size());
const failure = new Error("Unavailable");
const failed = reader.load("B");
await Promise.resolve();
operations[2].reject(failure);
try { await failed; } catch (error) { console.log("same failure", error === failure); }
console.log("after failure", reader.size());
const retry = reader.load("B");
await Promise.resolve();
operations[3].resolve("retried");
console.log(await retry, calls.join(","));
const throwing = createPendingReader(() => { throw failure; });
try { await throwing.load("X"); } catch (error) { console.log("sync failure", error === failure); }
console.log("cleaned", throwing.size());
try { reader.load(7); } catch (error) { console.log(error.message); }
// ✅ Expected output:
// shared true
// calls A
// forgot true
// old
// replacement retained true 1
// new 0
// same failure true
// after failure 0
// retried A,A,B,B
// sync failure true
// cleaned 0
// Key must be a stringEach load invocation closes over its key and promise; the factory owns the shared map. The old operation’s cleanup cannot erase the replacement because the identities differ. This helper has no timeout, cancellation, concurrency cap or user-interface publication policy. Those are separate contracts, not features supplied automatically by a closure.
Practice quiz
What does this complete program print? function make() { let shared = "A"; const read = () => shared; shared = "B"; return read; } console.log(make()());
- B
- A
- undefined
- ReferenceError
Answer: B. The function reads a live shared binding rather than a frozen initial value.
What does this complete program print? function badOnce(fn) { let result; return () => result || (result = fn()); } let calls = 0; const read = badOnce(() => { calls++; return 0; }); read(); read(); console.log(calls);
- 0
- 2
- 1
- 3
Answer: 2. Zero is falsey, so a truthiness-based cache runs the operation again.
What does this complete program print? const original = Promise.resolve(3); async function wrapped() { return original; } console.log(wrapped() === original); console.log(await wrapped());
- true 3
- false undefined
- false 3
- true undefined
Answer: false 3. An async wrapper adopts the result while returning a distinct promise.
What does this complete program print? const current = new Map(); const oldEntry = {}, newEntry = {}; current.set("A", newEntry); if (current.get("A") === oldEntry) current.delete("A"); console.log(current.get("A") === newEntry);
- false
- undefined
- TypeError
- true
Answer: true. An ownership guard prevents an older cleanup from deleting a newer entry.
What does this complete program print? const pending = new Map(); const operation = Promise.resolve("ready"); pending.set("A", operation); const first = pending.get("A"), second = pending.get("A"); console.log(first === second);
- true
- false
- undefined
- ready
Answer: true. Both lookups return the exact stored promise reference.
What does this complete program print? const error = new Error("Failed"); const original = Promise.reject(error); const cleaned = original.finally(() => {}); const results = await Promise.allSettled([original, cleaned]); console.log(results.map(result => result.status).join(","));
- fulfilled,rejected
- rejected,rejected
- rejected,fulfilled
- fulfilled,fulfilled
Answer: rejected,rejected. A successful finally preserves rejection in its separate returned promise.
What does this complete program print? const pending = new Map([["A", Promise.resolve("old")]]); console.log(pending.delete("A")); console.log(pending.has("A"));
- false true
- true true
- true false
- false false
Answer: true false. Removing the map entry changes tracking; it does not cancel the promise.
What does this complete program print? function makeReader(prefix) { return key => prefix + ":" + key; } const a = makeReader("first"), b = makeReader("second"); console.log(a("A"), b("A"));
- first:A first:A
- second:A second:A
- A:first A:second
- first:A second:A
Answer: first:A second:A. Each factory call owns a distinct prefix parameter binding.
Continue this course
- Previous: Deep Dive into JavaScript Execution Context & Call Stack
- Next: Event Loop, Microtasks & Async Internals — How the event loop, task queue, and microtask queue work together
- Quick reference: JavaScript cheat sheet