Technical skill practice
What Is a Closure in JavaScript? Test Independent Captured State
A closure lets a function retain access to its lexical environment after the surrounding function has returned. A small factory makes that state visible without relying on a global variable.
The task
Create two independent ticket counters with different starting points. Keep one returned function reference, call it repeatedly and check that the other counter’s state is unaffected.
Runnable Node 22 example
const assert = require('node:assert/strict');
function ticketCounter(start) {
let next = start;
return function () { return next++; };
}
const deskA = ticketCounter(40);
const deskB = ticketCounter(90);
const sameA = deskA;
assert.equal(deskA(), 40);
assert.equal(sameA(), 41);
assert.equal(deskB(), 90);
assert.equal(deskA(), 42);
assert.equal(typeof deskA, 'function');
console.log(`A-next=${deskA()}; B-next=${deskB()}`);
Expected output and explanation
Each call to the factory creates its own next binding. deskA and sameA refer to the same returned function and therefore advance the same counter. deskB belongs to a separate factory invocation and begins at ninety.
The factory has already returned when the counters are called, yet their functions can still access their respective next values. That continued access is the closure behavior being tested. The function reference is not the same thing as one numeric result returned by calling it.
Output from the example
A-next=43; B-next=91
Pitfall to check
Captured state can persist longer than expected if callbacks remain reachable. Keep the lifetime and sharing deliberate. This example demonstrates isolated in-memory counters, not a globally unique ticket allocation system across processes.
Questions, answered
Does assigning deskA to another variable copy its state?
No. It copies the reference to the same function. Call the factory again when you need another independent captured environment.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.