liveBook · Manning

Module pattern

As explained in Functional Programming in JavaScript

A JavaScript encapsulation pattern that exposes a public API while keeping internal state and helper functions hidden.

The module pattern packages related JavaScript behavior inside one immediately invoked function expression. It hides internal variables and helper functions while returning an object that exposes the intended public API, reducing global references. section 2.4

function zipCode(code, location) {
    let _code = code;
    let _location = location || '';

    return {
       code: function () {
         return _code;
       },
       location: function () {
          return _location;
       },
     ...
   };
}

A closure lets returned methods read private variables without exposing those variables directly. section 2.4

Private state behind public methods

A zip-code factory can retain its code privately and expose access through a method: const princetonZip = zipCode('08544', '3345'); princetonZip.code(); // '08544'. The caller uses the method, not the hidden variable. section 2.4

The pattern provides three practical benefits:

  • Encapsulates internal state and behavior. section 2.4
  • Limits the global namespace and shared data. section 2.4
  • Supports functional code organized into well-encapsulated modules. section 2.4

How Functional Programming in JavaScript covers it

How deep it goes
Explains IIFE encapsulation, closure access, private variables, exported methods, and reduced global references.
Examples
Uses a zip-code factory whose returned methods access hidden code and location variables.
What it assumes
Assumes basic JavaScript functions and objects while teaching closure-based privacy through function scope.
What you can do after
Apply closures and IIFEs to build JavaScript modules with hidden state and exposed behavior.
How it connects
Connects closures, function scope, encapsulation, immutability, global namespaces, and functional programming.

Also explained in

Compare how 2 books explain module pattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Functional Programming in JavaScript. The section links point to the parts of the book it draws on.