Skip to main content
XenonStack

Service Design

XenonStack Insights JavaScript Module Pattern: IIFE, Closures, ES Modules

| Published | Updated

JavaScript Module Pattern: IIFE, Closures, ES Modules
8:14
JavaScript module pattern: global scope, IIFE scope, closure with private state, public API object

Key takeaway

  • Learn the JavaScript module pattern: how an IIFE and closures create private state, how it compares with ES modules, and when to use each in your code.

The JavaScript module pattern wraps code in an immediately invoked function expression (IIFE) that returns an object, so the returned functions are public while every other variable and function stays private inside a closure. It gives plain scripts a form of encapsulation without any special syntax.

This guide is for front-end and Node.js developers who maintain older scripts or need to explain the pattern in a code review. It covers how the pattern works, how it compares with CommonJS, AMD and ES modules, its limits, and what to use today. JavaScript supports several styles, including functional programming, and the pattern relies on functions being first-class values.

What is the module pattern in JavaScript?

The module pattern is a design pattern for organising code. A function is defined and called at once, it declares private variables and helper functions, and it returns an object that exposes only the functions other code may use. The MDN page on closures describes this as emulating private methods: JavaScript, prior to classes, "didn't have a native way of declaring private methods, but it was possible to emulate private methods using closures", and it notes that such closures "follow the Module Design Pattern".

How does the module pattern work?

Two language features do the work. An IIFE, as the MDN glossary defines it, is "an idiom in which a JavaScript function runs as soon as it is defined". A closure is "the combination of a function bundled together (enclosed) with references to its surrounding state". The IIFE creates a private scope, and the returned functions keep access to it. The name is IIFE, sometimes miswritten as IFFI.

Two-column diagram. Inside the IIFE: function defined, private variables, private helpers, object returned. Outside: global scope, public calls only, closure access, direct access fails.
const counter = (function () {
  let privateCounter = 0;
  function changeBy(val) { privateCounter += val; }
  return {
    increment() { changeBy(1); },
    decrement() { changeBy(-1); },
    value() { return privateCounter; }
  };
})();

counter.increment();
console.log(counter.value()); // 1

This example follows the MDN closures page. As that page explains, you cannot reach privateCounter or changeBy from outside the anonymous function; you access them only through the three public functions that are returned. That is encapsulation: the object offers a small public interface and hides the rest.

Why did developers use it?

Classic scripts share one global scope, so a variable declared at the top level in one file can collide with another file's. MDN lists "avoiding polluting the global namespace by creating a new scope" as a use of IIFEs. The module pattern adds a clear public interface on top: another developer can see which functions are meant to be called and change the rest without breaking callers. That makes code easier to read, test through its public methods and hand over between teams.

How does it compare with other module approaches?

Before the language had its own modules, developers used several approaches. The MDN modules guide notes that Node.js has had module support for a long time and that libraries and tools enabled it elsewhere, naming AMD loaders such as RequireJS, bundlers such as webpack and compilers such as Babel.

ApproachHow it hides codeStatus and use
Object literalIt does not; every property is publicGroups related values, but offers no privacy
Module pattern (IIFE)Closure keeps private variables; a returned object is the public APIWorks in any script; common in older code
CommonJS and AMDEach file is a module loaded by a loader or runtimeCommonJS is the format Node.js has long used; AMD loaders such as RequireJS target the browser
ES modulesEach file runs in its own scope; only exported names are visibleThe language's own standard, used with import, export and type="module"

MDN states that ES modules are "automatically in strict mode", that they run "in their own scope, not in the global scope", and that variables are not visible outside a module "unless they are either explicitly exported" or attached to the global object. A script tag loads one with type="module", and the import() operator loads one on demand and returns a Promise.

What are the disadvantages of the module pattern?

  • Each call to the wrapping function creates new function objects, because closures are created every time a function is created. A module used as a single instance is fine, but a factory that builds thousands of objects holds a copy of its methods for each one.
  • Private members cannot be reached from outside, which also means tests and subclasses cannot reach them. Teams sometimes expose helpers just for testing, which defeats the purpose.
  • Dependencies are implicit: the pattern gives no way to declare what a module needs, so load order is managed by hand or by a bundler.
  • It is a convention, not a language feature, so static tools cannot see its exports as easily as they see import and export statements.

Which should you use today?

For new code, use ES modules: the language provides scope isolation, explicit exports and dependency declarations. Keep the module pattern for scripts that run without a bundler or module loader, or when you maintain older code. If you move a legacy module to ES modules, keep the public function names so callers do not change. Related reading: functional programming in JavaScript and Node.js versus Golang.

Which other JavaScript design patterns matter?

PatternWhat it is for
ConstructorCreates objects with shared setup
SingletonAllows only one instance, such as one shared configuration
ObserverLets many parts react when a subject changes
MediatorRoutes communication between parts through one object
PrototypeShares behaviour between objects through prototypes
CommandWraps a call, such as an API request, so callers do not depend on its details
FacadeOffers a simple interface over a more complex set of parts

See our guides to design patterns and Angular dependency injection, and see functional programming in Scala and functional testing and its types for neighbouring topics. For help shipping front-end code, see our digital product development and engineering services.

How do AI agents change the module question?

Coding agents read and edit JavaScript across a whole code base, so module boundaries now matter to machines as well as people. A file with explicit exports shows an agent which names are public, and a wrapper that hides state shows what it must not touch. Tests that call only the public interface give an agent a safe way to check its changes. ElixirClaw, the AI agents computing platform, is the page to read for running such agents in your engineering workflow.

What should you do first?

  1. Find global variables and functions shared across your scripts.
  2. Wrap one group of related code in an IIFE and return only the functions callers need.
  3. Write tests against the returned object, not the private helpers.
  4. Plan a move to ES modules with import and export, one file at a time.
  5. Document each module's public functions in a short comment at the top.

To map one decision your engineering agents make, and the code and policy it depends on, book a Context Workshop. See what happens in the workshop.

Frequently asked questions

What is the module pattern in JavaScript?

It is a pattern in which an immediately invoked function expression returns an object. The returned functions are public, and the variables and functions inside the wrapper stay private through closures.

What is the difference between the module pattern and ES modules?

The module pattern is a convention built from an IIFE and closures. ES modules are the language's own feature, with each file in its own scope and explicit import and export statements.

Is the module pattern still used?

It still appears in older code and in scripts loaded without a module system. New code normally uses ES modules.

Does the module pattern make variables truly private?

Variables inside the wrapper cannot be reached from outside, so they are private in practice. They are hidden by scope rather than by an access modifier.

What does IIFE stand for?

It stands for immediately invoked function expression, a function that runs as soon as it is defined.

Ready to put AI agents to work? See an ElixirClaw demo: the agentic OS to build, orchestrate and govern AI agents across your enterprise systems.

Table of Contents

navdeep-singh-gill

Navdeep Singh Gill

Global CEO and Founder of XenonStack

LinkedIn profile

Navdeep Singh Gill is serving as Chief Executive Officer and Product Architect at XenonStack. He holds expertise in building SaaS Platform for Decentralised Big Data management and Governance, AI Marketplace for Operationalising and Scaling. His incredible experience in AI Technologies and Big Data Engineering thrills him to write about different use cases and its approach to solutions.

Get the latest articles in your inbox

Subscribe Now

Interested in solving your challenges with the XenonStack team?
Get Started

Tell us about you and your priorities so we can prepare the right conversation. It takes about 2 minutes.

Please Select your Industry
Banking
Fintech
Payment Providers
Wealth Management
Discrete Manufacturing
Semiconductor
Machinery Manufacturing / Automation
Appliances / Electrical / Electronics
Elevator Manufacturing
Defense & Space Manufacturing
Computers & Electronics / Industrial Machinery
Motor Vehicle Manufacturing
Food and Beverages
Distillery & Wines
Beverages
Shipping
Logistics
Mobility (EV / Public Transport)
Energy & Utilities
Hospitality
Digital Gaming Platforms
SportsTech with AI
Public Safety - Explosives
Public Safety - Firefighting
Public Safety - Surveillance
Public Safety - Others
Media Platforms
City Operations
Airlines & Aviation
Defense Warfare & Drones
Robotics Engineering
Drones Manufacturing
AI Labs for Colleges
AI MSP / Quantum / AGI Institutes
Retail Apparel and Fashion

Continue