← Back to Engine

Lexical Scope & Closures


A closure is a function bundled together with references to its surrounding lexical environment. It allows an inner function to retain access to variables from its outer enclosing scope even after the outer function has finished executing and popped off the Call Stack.

1. How V8 Manages Closures

When an inner function references outer variables, V8 moves those variables from the short-lived Call Stack frame to a persistent Closure Context allocated on the Heap. The inner function retains an internal [[Environment]] property pointing to that Heap context.

2. Primary Use Cases

  • Data Privacy & Encapsulation: Hide private state so it cannot be directly mutated or inspected from outside.
  • Function Factories: Generate tailored functions pre-configured with specific parameters.
  • Partial Application & Currying: Break multi-argument functions into sequential single-argument invocations.

3. Memory Warning

Variables held in a closure cannot be garbage collected while the inner function reference lives. Be mindful of stale references in long-lived event handlers or global callbacks!


The Challenge: Encapsulated State Store

Implement a function createEncapsulatedState(initialValue) that creates a private state store utilizing closures. The returned object must feature:

  1. getValue(): Returns current state.
  2. setValue(val): Updates current state and records val in a private history log array.
  3. getHistory(): Returns a copy of the private history array.
  4. State variables must be strictly hidden inside the closure (not directly accessible on the returned object).