SyntaxPilot
Courses/JavaScript Coding Questions/Lesson 17
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

JavaScript Coding Questions · Lesson 17 of 30

Closure questions

counter factoryonce(fn)memoize(fn) with a Map; the shared-variable trap

These are the notes for JavaScript Coding Questions, episode 17, interview and placement practice for people who finished the SyntaxPilot JavaScript course. Today is all about closures, with three questions interviewers love: build a counter factory, write once(fn) so a function runs only one time, and write memoize(fn) so a slow function never repeats work. Plus the most famous closure trap: a loop where every function shares one variable (var vs let).

Each question follows the same steps: read the problem, think out loud, the obvious attempt, a real failure, why, the fix, every test case, and the complexity.

Every program was run with Node.js 24 (node main.js), the SyntaxPilot compiler's JavaScript command, and every output below is real. Plain modern JavaScript, no packages.

Q1: A counter factory

Problem. makeCounter(name) returns a new counter function. Every counter counts on its own, and nobody outside can change its number.

billing() → "B-1", billing() → "B-2", pharmacy() → "P-1", billing() → "B-3"

Real life: a clinic with a token machine at every counter.

Think out loud

  • Edge cases: two counters running at the same time; code elsewhere must not be able to reset or change a count.

Attempt: one global count

let count = 0;
function nextToken() {
  count = count + 1;
  return count;
}
console.log("Billing:", nextToken(), nextToken());
console.log("Pharmacy:", nextToken());
count = 100;
console.log("Billing:", nextToken());
Billing: 1 2
Pharmacy: 3
Billing: 101

There is only one count, at the top level of the file: a global variable. Every counter shares it (pharmacy gets 3, not 1), and any line anywhere can change it (count = 100).

The idea: a closure

A closure is a function together with the variables it remembers from the place where it was created. When an inner function uses a variable of the outer function, that variable stays alive as long as the inner function exists, even after the outer function has returned. Think of it as the function's backpack.

Real life: a factory (makeCounter) builds a token machine for each counter. Each machine has its own roll of numbers sealed inside its case (let count). Press the button (billing()) and it prints the next token from its own roll. Nobody can reach in.

function makeCounter(name) {
  let count = 0;
  return function () {
    count = count + 1;
    return `${name}-${count}`;
  };
}
const billing = makeCounter("B");
const pharmacy = makeCounter("P");
console.log(billing(), billing(), pharmacy(), billing());
console.log(billing.count, typeof count);
B-1 B-2 P-1 B-3
undefined undefined
  • Every call to makeCounter runs its body again, so it creates a new count. The returned function closes over that one count, so the two counters never mix.
  • count is not a property of the function (billing.count is undefined) and it doesn't exist outside (typeof count is "undefined", no error: typeof is safe on undeclared names). The state is private.
  • `${name}-${count}` is a template string: backticks, with ${ } for values.

A counter with more than one button

function makeCounter(start = 0) {
  let count = start;
  return {
    next: () => ++count,
    reset: () => { count = start; },
    get value() { return count; },
  };
}
const c = makeCounter(10);
c.next(); c.next();
console.log(c.value);
c.reset();
console.log(c.value, c.next());
c.value = 99;
console.log(c.value);
12
10 11
11
  • All three functions close over the same count.
  • get value() is a getter: a property that runs a function when you read it. With no setter, c.value = 99 is silently ignored in normal scripts. In strict mode ("use strict"; at the top, and always inside classes and ES modules) it throws:
TypeError: Cannot set property value of #<Object> which has only a getter
  • ++count adds one and gives the new value (count++ would give the old one).

Complexity: every call is O(1) time; each counter keeps O(1) memory.

The shared-variable trap: var in a loop

A cinema app makes one button per seat in a loop. Predict the output first.

const buttons = [];
for (var i = 1; i <= 3; i++) {
  buttons.push(() => console.log("Seat", i));
}
buttons.forEach((press) => press());
for (var j = 1; j <= 3; j++) {
  setTimeout(() => console.log("Timer", j), 0);
}
Seat 4
Seat 4
Seat 4
Timer 4
Timer 4
Timer 4
  • var creates one variable for the whole function (or file), not one per round of the loop. All three closures share that same i.
  • They run after the loop has finished, and the loop stopped when i became 4 (the first value that failed i <= 3).
  • setTimeout(fn, 0) runs fn later, after the current code finishes, so it shows the same problem.

Fix: let. A let in a for header creates a new binding (a fresh variable) for every round, so each closure gets its own copy.

const buttons = [];
for (let i = 1; i <= 3; i++) {
  buttons.push(() => console.log("Seat", i));
}
buttons.forEach((press) => press());
for (let j = 1; j <= 3; j++) {
  setTimeout(() => console.log("Timer", j), 0);
}
Seat 1
Seat 2
Seat 3
Timer 1
Timer 2
Timer 3

Before let existed (2015), people fixed it with an IIFE (an immediately invoked function expression) that gave each round its own parameter:

const buttons = [];
for (var i = 1; i <= 3; i++) {
  ((seat) => buttons.push(() => console.log("Seat", seat)))(i);
}
buttons.forEach((press) => press());
Seat 1
Seat 2
Seat 3

Q2: Run a function only once

Problem. once(fn) returns a function that calls fn the first time only. Every later call returns the first result again, without running fn.

Real life: a Pay button tapped twice on a slow network must charge once.

Think out loud

  • Edge cases: what later calls return, later calls with different arguments, and this when the function is a method.

The problem

let charged = 0;
function pay(amount) {
  charged += amount;
  return { id: "TXN" + charged, amount };
}
pay(499);
pay(499);
console.log("Charged:", charged);
Charged: 998

Attempt: a flag in a closure

function once(fn) {
  let called = false;
  return function (...args) {
    if (called) return;
    called = true;
    return fn(...args);
  };
}
let charged = 0;
const pay = once((amount) => {
  charged += amount;
  return { id: "TXN" + charged, amount };
});
console.log(pay(499));
console.log("Charged:", charged);
console.log(pay(499).id);
{ id: 'TXN499', amount: 499 }
Charged: 499
TypeError: Cannot read properties of undefined (reading 'id')

The flag works (only 499 is charged), but the second call hits a bare return, which returns undefined. The app expected the same transaction back, and reading id of undefined throws.

  • ...args in the parameters is a rest parameter: it collects all arguments into an array. fn(...args) spreads them back out.

Fix: store the result, and keep this

function once(fn) {
  let called = false, result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}
let charged = 0;
const pay = once((amount) => {
  charged += amount;
  return { id: "TXN" + charged, amount };
});
console.log(pay(499).id, pay(499).id, pay(10).id);
console.log("Charged:", charged);
const shop = {
  name: "Chai Point",
  open: once(function () { return this.name + " is open"; }),
};
console.log(shop.open(), shop.open());
TXN499 TXN499 TXN499
Charged: 499
Chai Point is open Chai Point is open
  • fn.apply(thisValue, argsArray) calls fn with a chosen this and an array of arguments. Our wrapper is a normal function, so when it is called as shop.open(), its this is shop, and apply passes it on. With fn(...args), this inside the method would be undefined, and this.name would throw.
  • Set called = true before calling fn: if fn calls the wrapper again (re-entry), it won't run twice.

Complexity: O(1) time per call, O(1) space (one flag, one result).

Q3: Memoize a slow function

Problem. memoize(fn) remembers each answer. When the same arguments come again, return the saved answer instead of computing it again. Saving answers like this is memoization; the saved answers are a cache.

Real life: a shopkeeper writes each price on a rate card instead of recalculating it for every customer, and he must write the whole question ("5 km at ₹12 → ₹60"), not just "5 km".

The slow function

let calls = 0;
function fib(n) {
  calls++;
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
console.log(fib(30), "calls:", calls);
calls = 0;
console.log(fib(30), "calls:", calls);
832040 calls: 2692537
832040 calls: 2692537

Naive recursive Fibonacci calls itself twice per step, so the work roughly doubles with each n (about O(1.6ⁿ)), and it repeats all of it every time.

Attempt: a Map keyed by the first argument

function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = args[0];
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}
const fare = memoize((km, rate) => km * rate);
console.log(fare(5, 12));
console.log(fare(5, 20));
console.log(fare(8, 12));
60
60
96

fare(5, 20) should be 100. The key was only the first argument, 5, so the second call found the old answer. A wrong answer is worse than a slow one: the key must include every argument.

Fix 1: the key from all arguments

function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) return cache.get(key);
    const result = fn(...args);
    cache.set(key, result);
    return result;
  };
}
const fare = memoize((km, rate) => km * rate);
console.log(fare(5, 12), fare(5, 20), fare(5, 12));
let calls = 0;
function fib(n) {
  calls++;
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
}
const fastFib = memoize(fib);
console.log(fastFib(30), "calls:", calls);
calls = 0;
console.log(fastFib(30), "calls:", calls);
calls = 0;
console.log(fastFib(31), "calls:", calls);
60 100 60
832040 calls: 2692537
832040 calls: 0
1346269 calls: 4356617
  • JSON.stringify([5, 12]) is "[5,12]", a different key from "[5,20]". (It works for numbers, strings, booleans and plain data; objects with the same content but different identity get the same key, and functions can't be keys this way.)
  • The repeat fastFib(30) is free. But a new fastFib(31) takes 4.3 million calls: inside fib, the recursive calls go to fib, the original, not to fastFib. Only the outermost call ever checks the cache.

Fix 2: memoize the recursive function itself

function memoize(fn) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (!cache.has(key)) cache.set(key, fn(...args));
    return cache.get(key);
  };
}
let calls = 0;
const fib = memoize((n) => {
  calls++;
  return n < 2 ? n : fib(n - 1) + fib(n - 2);
});
console.log(fib(30), "calls:", calls);
calls = 0;
console.log(fib(50), "calls:", calls);
832040 calls: 31
12586269025 calls: 20

Now fib is the memoized version, so every inner call checks the cache. fib(30) needs 31 calls (one per n from 0 to 30); fib(50) needs only 20 more, because 0 to 30 are already cached.

Complexity: memoized fib(n): O(n) time, O(n) space for the cache (and O(n) recursion depth). Memoize trades memory for speed; the cache grows with every new input, so use it for functions that are pure (same input → same output, no side effects), slow, and called with repeating arguments.

Complexity summary

Function Time per call Space
Counter (closure) O(1) O(1) per counter
once(fn) O(1) + fn the first time O(1)
memoize(fn) lookup O(size of the key) O(number of distinct inputs)
Naive fib(n) about O(1.6ⁿ) O(n) stack
Memoized fib(n) O(n) the first time O(n)

Common mistakes (and the exact outputs)

Mistake Code What you see Why Fix
A global counter let count = 0 at the top Pharmacy: 3, then 101 one shared, public variable a counter factory
var in a loop with callbacks for (var i ...) push(() => i) Seat 4 three times one i for every closure for (let i ...)
Writing to a getter c.value = 99 ignored; in strict mode TypeError: Cannot set property value of #<Object> which has only a getter no setter add a method like reset()
once with a bare return if (called) return; TypeError: Cannot read properties of undefined (reading 'id') later calls return undefined store and return result
fn(...args) for methods once(function () { this.name }) this is undefined the call has no receiver fn.apply(this, args)
Key from one argument const key = args[0] fare(5, 20) → 60 other arguments ignored JSON.stringify(args)
Memoizing a recursive function from outside memoize(fib) 4356617 calls for a new n inner calls skip the cache const fib = memoize((n) => ... fib(n - 1) ...)

Mini project: an OTP service with a limit per phone

A closure can hold more than a number: here a Map of how many codes each phone got, private to the service.

function makeOtpService(maxPerPhone) {
  const sent = new Map();
  let nextCode = 4821;
  return {
    send(phone) {
      const count = sent.get(phone) ?? 0;
      if (count >= maxPerPhone) return `${phone}: limit reached`;
      sent.set(phone, count + 1);
      return `${phone}: code ${nextCode++} (${count + 1}/${maxPerPhone})`;
    },
    stats: () => Object.fromEntries(sent),
  };
}
const otp = makeOtpService(2);
console.log(otp.send("A"));
console.log(otp.send("A"));
console.log(otp.send("A"));
console.log(otp.send("B"));
console.log(otp.stats(), otp.sent);
A: code 4821 (1/2)
A: code 4822 (2/2)
A: limit reached
B: code 4823 (1/2)
{ A: 2, B: 1 } undefined

(A real service would use random codes and time windows; the counting idea is the same.)

Your turn: a rate limiter (solution)

Problem. limit(fn, n) lets fn run at most n times; after that it returns "limit reached".

function limit(fn, n) {
  let count = 0;
  return function (...args) {
    if (count >= n) return "limit reached";
    count++;
    return fn.apply(this, args);
  };
}
const sendOtp = limit((phone) => `OTP sent to ${phone}`, 3);
for (let i = 0; i < 4; i++) console.log(sendOtp("98xxxxxx10"));
const once = (fn) => limit(fn, 1);
const hello = once(() => "hello");
console.log(hello(), hello());
OTP sent to 98xxxxxx10
OTP sent to 98xxxxxx10
OTP sent to 98xxxxxx10
limit reached
hello limit reached

limit(fn, 1) runs fn once like once, but notice the difference: our real once returns the first result again, while limit returns "limit reached". Pick what the caller needs. O(1) time and space.

Practice questions (with solutions)

1. A counter with a step and a maximum.

Solution
function makeCounter({ start = 0, step = 1, max = Infinity } = {}) {
  let count = start;
  return () => {
    if (count + step > max) return count;
    count += step;
    return count;
  };
}
const token = makeCounter({ start: 100, step: 5, max: 115 });
console.log(token(), token(), token(), token());
105 110 115 115

The options object with defaults ({ start = 0, ... } = {}) lets you call makeCounter() with nothing at all.

2. memoize that keeps only the last maxSize answers (an LRU cache).

Solution
function memoize(fn, maxSize = 100) {
  const cache = new Map();
  return function (...args) {
    const key = JSON.stringify(args);
    if (cache.has(key)) {
      const value = cache.get(key);
      cache.delete(key);
      cache.set(key, value);
      return value;
    }
    const value = fn(...args);
    cache.set(key, value);
    if (cache.size > maxSize) cache.delete(cache.keys().next().value);
    return value;
  };
}
let work = 0;
const square = memoize((n) => { work++; return n * n; }, 2);
square(2); square(3); square(2); square(4); square(3);
console.log("computed", work, "times");
computed 4 times

A Map remembers insertion order. Deleting and re-inserting a key on every hit moves it to the end, so the first key is always the least recently used (LRU), and that's the one removed. Here: 2, 3 computed; 2 is a hit; 4 is computed and 3 is evicted; 3 is computed again: 4 times.

3. A once that can be reset.

Solution
function once(fn) {
  let called = false, result;
  const wrapper = function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
  wrapper.reset = () => { called = false; result = undefined; };
  return wrapper;
}
let n = 0;
const connect = once(() => ++n);
console.log(connect(), connect());
connect.reset();
console.log(connect(), connect());
1 1
2 2

Functions are objects, so you can attach a method (wrapper.reset) that shares the same closure.

4. Fix the var loop without changing var to let.

Solution

Give each round its own variable with a function parameter (an IIFE), as shown in the trap section, or use buttons.forEach / Array.from({ length: 3 }, (_, k) => ...), where each callback call has its own parameter.

Quick quiz

const fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
let out = "";
for (let j = 0; j < 3; j++) out += fns[j]();
console.log(out, typeof i);

A) 012 undefined B) 333 number C) 012 number D) 333 undefined

Answer

B, output 333 number. All three closures share the one var i, which ended at 3. var is not limited to the loop block, so i still exists afterwards and typeof i is "number".

Interview questions

  1. What is a closure? A function plus the variables it captured from the scope where it was created; those variables live as long as the function does.
  2. Give a practical use of closures. Private state (counters, caches), function factories, once, memoize, debounce, event handlers that remember data.
  3. Why does var in a loop print the last value? var is function-scoped: one variable shared by all callbacks. let is block-scoped and gets a new binding per iteration.
  4. Can closures cause memory leaks? A closure keeps its captured variables alive. A long-lived closure (an event listener, a global cache) holding a large object keeps it in memory; remove listeners and bound caches when done.
  5. What should once return on later calls? Usually the first result, so callers can rely on a value.
  6. When is memoization wrong? For impure functions (random numbers, time, network, side effects), for keys that don't capture all inputs, and when the cache grows without limit.
  7. Difference between call, apply? Both set this; call(thisArg, a, b) takes arguments one by one, apply(thisArg, [a, b]) takes an array. (Episode 19 writes both.)

Glossary

Term Meaning
Closure A function together with the variables it remembers from where it was created
Scope The part of the code where a variable can be used
Global variable A variable at the top level, visible to (and changeable by) all code
Factory function A function that builds and returns new objects or functions (makeCounter)
Private state Data only the closure's own functions can reach
Template string A string in backticks with ${ } for values
Getter get value() { ... }: a property that runs a function when read
Strict mode "use strict": stricter rules; silent mistakes become errors
var Old variable keyword: function-scoped, one variable for a whole loop
let Block-scoped variable; in a for header, a new binding per iteration
Binding The connection between a variable name and its storage
setTimeout(fn, ms) Runs fn later, after at least ms milliseconds
IIFE Immediately invoked function expression: ((x) => ...)(value)
Rest parameter ...args in a parameter list: collects arguments into an array
Spread fn(...args): passes array items as separate arguments
fn.apply(thisArg, args) Calls fn with a chosen this and an array of arguments
this The object a normal function was called on (shop in shop.open())
Memoization Saving each result so the same input never computes twice
Cache The store of saved results (here a Map)
Cache key The value that identifies an input; must include every argument
Pure function Same input → same output, with no side effects
LRU Least recently used: the cache entry to evict first
Fibonacci 0, 1, 1, 2, 3, 5, …: each number is the sum of the two before
Big-O How the work grows with the input size

Summary

  • A closure is a function plus the variables it remembers. Each call to a factory creates new variables, which gives every counter its own private count.
  • var in a loop shares one variable among all callbacks; let creates a new one per iteration.
  • once(fn) keeps a flag and the first result in its closure, and uses fn.apply(this, args) so methods keep their this.
  • memoize(fn) keeps a Map; the key must come from every argument (JSON.stringify(args)), and a recursive function must call the memoized version to benefit.
  • Next episode: debounce, throttle, curry, compose and pipe.