javascript Patterns
Module Patterns
-
What it is: This is a way to encapsulate code into self-contained units, exposing only a public API while keeping private variables and functions hidden. Think of it like a black box – you know what goes in and what comes out, but you don’t need to worry about the messy bits inside.
-
Why it’s hot: It helps you avoid global scope pollution (which can lead to nasty conflicts!), promotes code organization, and creates private members. This is fundamental for building robust applications and preventing unintended side effects. With ES Modules (ESM) now standard, this pattern is even more accessible and widely used.
-
example (classic IIEF):
const myModule = (function() { let privateVariable = 'I am private!'; function privateMethod() { console.log(privateVariable); } return { publicMethod: function() { console.log('I am public!'); privateMethod(); }, publicProperty: 'I am a public property' }; })(); myModule.publicMethod(); // "I am public!" followed by "I am private!" // console.log(myModule.privateVariable); // undefined -
example (modern ES Module):
// myModule.js let privateVariable = 'I am private!'; function privateMethod() { console.log(privateVariable); } export function publicMethod() { console.log('I am public!'); privateMethod(); } export const publicProperty = 'I am a public property'; // app.js import { publicMethod } from './myModule.js'; publicMethod();