← DEVLOG
Tech Notes2021.05.024 min read

JavaScript Module Pattern and Closures

Closure as a language mechanism, the module pattern built on top of it — private/public separation via lexical scope, with a note on memory leaks.

javascriptclosuremodule-patternencapsulation

Restored from a 2021-05 archive.

The JavaScript module pattern is one approach to code organization and object handling. It uses scope to distinguish between private and public — think of it as a namespace pattern plus lexical scoping.

JavaScript has no built-in access modifiers (private, public, protected, default). The module pattern is the primary technique for simulating encapsulation. It avoids polluting the global namespace, typically defining private variables and functions inside a function body, and treating the return value as the public API.

The module pattern combines these patterns:

  • Namespace pattern
  • Immediately Invoked Function Expression (IIFE)
  • Private / public members
  • Explicit dependency declaration

One common way to construct a module is using JavaScript's closure.

Closure and the Module Pattern

A closure is an inner function that has access to its outer function, or the principle that allows this. Inner functions can access variables and functions in their enclosing scope, but the outer function cannot reach into the inner function's scope.

When a function is declared in JavaScript, it remembers the scope it has access to — the lexical scope. An inner function that retains access to its enclosing outer function's environment is a closure.

The key insight: the outer function's local variables live as long as there's an inner function using them, outliving the outer function's own execution. Normally local variables die when the function returns, but when an inner function keeps referring to them, the engine keeps them alive so the inner function can still access them. This mechanism is what makes encapsulated modules possible.

Closure — Core Definition

  • The relationship between outer and inner functions, and the prolonged lifecycle of outer variables that inner functions reference — all of this together is a closure
  • Enables private-like variables inside a function
  • Lets you implement getter/setter-style APIs using inner functions

Module Pattern via Closure

  • Use an IIFE or a new-keyword instance to build an encapsulated module
  • Define private elements usable only internally, and expose public elements externally

Memory Caution

If a closure keeps referencing variables over long periods, it can cause performance degradation — a classic memory leak. When an inner function is no longer needed, explicitly releasing the outer references (e.g. setting them to null) is a good practice.

Guestbook

Leave a short note about this post

0 / 140

Loading...