Module Scope Encapsulation
What you'll learn: How to keep helper functions and constants private within a module by simply not exporting them.
The Core Idea
When you work with ES modules (files with import and export), everything declared at the top level of your module file is already private by default. Only what you explicitly export becomes visible to other files. This gives you a powerful, clean way to hide implementation details without needing closures, WeakMaps, or private fields.
Think of your module like a restaurant kitchen: only the dishes (exports) leave the kitchen. The prep stations, ingredient storage, and cooking techniques (private functions and constants) stay behind the scenes.
How It Works
// userService.js
// Private helper - not exported
function validateEmail(email) {
return email.includes('@');
}
// Private constant - not exported
const MAX_LOGIN_ATTEMPTS = 3;
// Public API - exported
export function createUser(name, email) {
if (!validateEmail(email)) {
throw new Error('Invalid email');
}
return { name, email, attempts: 0 };
}
When another file imports from userService.js, it can only access createUser. The validateEmail function and MAX_LOGIN_ATTEMPTS constant are completely invisible outside the module—they're encapsulated at the module scope.
// app.js
import { createUser } from './userService.js';
createUser('Alice', 'alice@example.com'); // ✓ works
validateEmail('test'); // ✗ ReferenceError: not defined
Why This Matters
Module scope encapsulation is the simplest, most maintainable form of privacy in modern JavaScript. You don't need special syntax or patterns—just don't export what should stay internal.
Key Takeaway: In ES modules, privacy is the default—only exported declarations are public, making module scope the cleanest way to encapsulate implementation details.