JavaScript Closures and Private State Quiz
Build the classic closure patterns: encapsulated counters, lexical-scope inheritance through nested functions, and constructor-level private fields.
Question Bank
Medium
JavaScript
4 questions
quiz
closures
js-lexical-scope
interview-prep
417 views
12
Implement createCounter() so the returned object exposes increment, decrement, and getCount while keeping count private (untouchable from the outside).
Examples
Example 1:
Input: const c = createCounter(); c.increment(); c.increment(); c.decrement(); c.getCount()
Output: 1
Explanation: `count` lives in the closure scope of `createCounter`; only the returned methods can reach it.function createCounter() {
// your code here
}
const counter = createCounter();
counter.increment(); // 1
counter.decrement(); // 0Predict what inner() logs and explain how lexical scope keeps outerVar alive after outerFunction returns.
Examples
Example 1:
Input: const inner = outerFunction(); inner();
Output: 'I am from the outer function'
Explanation: `innerFunction` was defined inside `outerFunction`, so it closes over `outerVar`. The variable survives because the closure still references it.function outerFunction() {
let outerVar = 'I am from the outer function';
function innerFunction() {
console.log(outerVar);
}
return innerFunction;
}
const inner = outerFunction();
inner();Use a closure inside the Car constructor to make odometer private. Allow updates only through drive(miles) and reads through readOdometer().
Examples
Example 1:
Input: const c = new Car('Toyota', 'Corolla'); c.drive(50); c.readOdometer();
Output: 50
Explanation: `odometer` is a local variable in the constructor's closure, accessible only through the two methods.function Car(make, model) {
// your code here
}Write makeAdder(x) that returns a function which adds x to its argument. Then explain why each call to makeAdder produces an independent closure.
Examples
Example 1:
Input: const add5 = makeAdder(5); const add10 = makeAdder(10); add5(2) + add10(2)
Output: 19
Explanation: `add5` and `add10` each close over their own `x`, so they don't share state.function makeAdder(x) {
// your code here
}