Question Bank
JavaScript Closures and Private State Quiz
Difficulty: Medium
Build the classic closure patterns: encapsulated counters, lexical-scope inheritance through nested functions, and constructor-level private fields.
JavaScript Closures and Private State Quiz
Build the classic closure patterns: encapsulated counters, lexical-scope inheritance through nested functions, and constructor-level private fields.
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.Predict 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.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.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.