JavaScript · Syntax · Advanced
Closures and Scope
Lexical scope, closures, private state, and closure-based patterns
Quick topic start and explanations before exercises (exercises below):
Private state, once, and memoize patterns
#partial, debounce, compose/pipe, and closure patterns reference
#Exercises:
Implement a closure-based counter
#Implement `makeCounter()` that returns an object with `increment()`, `decrement()`, `reset()`, and `value()` methods. The counter state must be private — not accessible directly on the returned object.
function makeCounter() {
// return object with increment, decrement, reset, value
}
Solution
function makeCounter() {
let count = 0;
return {
increment() { return ++count; },
decrement() { return --count; },
reset() { count = 0; },
value() { return count; },
};
}
const c = makeCounter();
c.increment(); // 1
c.increment(); // 2
c.decrement(); // 1
c.value(); // 1
c.reset();
c.value(); // 0
Fix the var-in-loop closure bug
#The code below logs `3, 3, 3` instead of `0, 1, 2`. Explain why, and provide two fixes: one using `let`, one using an IIFE.
// This logs 3, 3, 3 — fix it to log 0, 1, 2
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
Solution
// Fix 1: use let (each iteration gets its own block-scoped i)
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0); // 0, 1, 2
}
// Fix 2: IIFE to capture i per iteration
for (var i = 0; i < 3; i++) {
(function(j) {
setTimeout(() => console.log(j), 0);
})(i);
}
Implement the once() higher-order function
#Implement `once(fn)` that returns a wrapper function. The wrapper calls `fn` only on the first invocation, then returns the cached result for all subsequent calls without calling `fn` again.
function once(fn) {
// fn should only be called the first time
// subsequent calls return the cached result
}
Solution
function once(fn) {
let called = false;
let result;
return function(...args) {
if (!called) {
called = true;
result = fn(...args);
}
return result;
};
}
const init = once(() => { console.log('initialising'); return 42; });
init(); // logs 'initialising', returns 42
init(); // returns 42, no log
Implement memoize()
#Implement `memoize(fn)` that returns a memoized version of `fn`. On the first call with a given set of arguments the result is computed and cached. On subsequent calls with the same arguments the cached value is returned directly.
function memoize(fn) {
// cache results keyed by arguments
}
Solution
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);
};
}
const slowSquare = memoize(n => { console.log('computing'); return n * n; });
slowSquare(5); // 'computing' → 25
slowSquare(5); // → 25 (no log, from cache)
slowSquare(6); // 'computing' → 36
Implement partial application
#Implement `partial(fn, ...presetArgs)` that returns a new function with `presetArgs` pre-filled. When the returned function is called with additional arguments, they are appended after the preset ones.
function partial(fn, ...presetArgs) {
// return a function with presetArgs pre-filled
}
Solution
function partial(fn, ...presetArgs) {
return function(...laterArgs) {
return fn(...presetArgs, ...laterArgs);
};
}
const multiply = (a, b) => a * b;
const double = partial(multiply, 2);
const triple = partial(multiply, 3);
double(5); // 10
triple(5); // 15
const greet = (greeting, name) => `${greeting}, ${name}!`;
const sayHi = partial(greet, 'Hi');
sayHi('Alice'); // 'Hi, Alice!'
Create a bank account with private balance
#Implement `makeBankAccount(initialBalance)` using a closure to keep `balance` private. Return an object with `deposit(amount)`, `withdraw(amount)`, and `getBalance()`. `deposit` should throw if amount ≤ 0; `withdraw` should throw if amount exceeds balance.
function makeBankAccount(initialBalance) {
// balance must be private
// return { deposit, withdraw, getBalance }
}
Solution
function makeBankAccount(initialBalance) {
let balance = initialBalance;
return {
deposit(amount) {
if (amount <= 0) throw new Error('Deposit must be positive');
balance += amount;
return balance;
},
withdraw(amount) {
if (amount > balance) throw new Error('Insufficient funds');
balance -= amount;
return balance;
},
getBalance() { return balance; },
};
}
const acc = makeBankAccount(100);
acc.deposit(50); // 150
acc.withdraw(30); // 120
acc.getBalance(); // 120
acc.balance; // undefined — private
Implement makeAdder() factory
#Implement `makeAdder(n)` that returns a function. The returned function takes one argument `x` and returns `x + n`. Each call to `makeAdder` should create an independent adder that remembers its own `n`.
function makeAdder(n) {
// return a function that adds n to its argument
}
Solution
function makeAdder(n) {
return function(x) {
return x + n;
};
}
const add5 = makeAdder(5);
const add10 = makeAdder(10);
add5(3); // 8
add5(7); // 12
add10(3); // 13
add10(add5(2)); // 17 (add5(2)=7, add10(7)=17)
Implement debounce()
#Implement `debounce(fn, delay)` that returns a debounced version of `fn`. The debounced function delays calling `fn` until `delay` milliseconds have passed since its last invocation. If called again before the delay expires, the timer resets.
function debounce(fn, delay) {
// return a debounced version of fn
// fn should only be called delay ms after the last invocation
}
Solution
function debounce(fn, delay) {
let timerId;
return function(...args) {
clearTimeout(timerId);
timerId = setTimeout(() => fn(...args), delay);
};
}
const handleInput = debounce((value) => {
console.log('searching for:', value);
}, 300);
// Fast typing — only the last call fires after 300ms:
handleInput('h');
handleInput('he');
handleInput('hel');
handleInput('hell');
handleInput('hello');
// After 300ms: 'searching for: hello'
Implement compose() and pipe()
#Implement `compose(...fns)` that applies functions right-to-left: `compose(f, g, h)(x)` is equivalent to `f(g(h(x)))`. Then implement `pipe(...fns)` that does the same left-to-right.
// compose(f, g)(x) === f(g(x))
// compose(f, g, h)(x) === f(g(h(x)))
function compose(...fns) {
// right-to-left execution
}
Solution
function compose(...fns) {
return function(x) {
return fns.reduceRight((v, f) => f(v), x);
};
}
const double = x => x * 2;
const addOne = x => x + 1;
const square = x => x * x;
const transform = compose(double, addOne, square);
// square(3)=9, addOne(9)=10, double(10)=20
transform(3); // 20
// pipe: left-to-right
const pipe = (...fns) => x => fns.reduce((v, f) => f(v), x);
const clean = pipe(s => s.trim(), s => s.toLowerCase());
clean(' HELLO '); // 'hello'
Predict closure output and explain
#What does this code log? Explain why each closure produces its result independently without interfering with the others. ```js function makeMultiplier(x) { return function(y) { return x * y; }; } const triple = makeMultiplier(3); const quadruple = makeMultiplier(4); console.log(triple(5)); console.log(quadruple(5)); console.log(triple(quadruple(2))); ```
function makeMultiplier(x) {
return function(y) {
return x * y;
};
}
const triple = makeMultiplier(3);
const quadruple = makeMultiplier(4);
console.log(triple(5));
console.log(quadruple(5));
console.log(triple(quadruple(2)));
Solution
// triple(5) → 3 * 5 = 15
// quadruple(5) → 4 * 5 = 20
// quadruple(2) = 8; triple(8) = 3 * 8 = 24
// Output: 15, 20, 24
// Why: each call to makeMultiplier creates a new closure
// capturing its own 'x'. triple closes over x=3,
// quadruple closes over x=4. They don't share state.